:::

9-3 useRoute 及 useRouter

  1. 範例(\src\views\Courses\_id.vue):
    <script>
    import axios from "axios";
    import { onMounted, onUnmounted, reactive, ref } from "vue";
    import { useRoute, useRouter } from "vue-router";
    export default {
      setup() {
        const route = useRoute();
        const router = useRouter();
        const pageDetal = reactive({ data: {} });
        const isError = ref(false);
        let timer = null;
    
        onMounted(() => {
          axios
            .get(`https://vue-lessons-api.herokuapp.com/courses/${route.params.id}`)
            .then((res) => {
              pageDetal.data = res.data.data[0];
            })
            .catch((error) => {
              isError.value = true;
              pageDetal.data["error_message"] = error.response.data.error_message;
              timer = setTimeout(() => {
                router.go(-1);
              }, 3000);
            });
        });
    
        onUnmounted(() => {
          clearTimeout(timer);
        });
    
        return { pageDetal, isError };
      },
    };
    </script>
    <template>
      <div>
        <div v-if="!isError">
          <h1>{{ pageDetal.data.name }}</h1>
          <h2>NTD: {{ pageDetal.data.money }}</h2>
          <img :src="pageDetal.data.photo" alt="" />
          <div>
            <img :src="pageDetal.data.teacher?.img" alt="" />
            <p>{{ pageDetal.data.teacher?.name }}</p>
          </div>
        </div>
        <h1 v-if="isError">{{ pageDetal.data.error_message }}</h1>
      </div>
    </template>
    
    <style></style>
    

     

  2. useRoute()取得所有 route 傳入的資料(在 route.params 中,例如 route.params.id):
    1. 傳入的參數:route.params
    2. 傳庫的網址:route.path
  3. useRouter()提供操作網址用的函式(例如: router.push("\Home") 用來轉向):
    1. 簡易轉向:
      router.push("\Home") 

       

    2. 轉向還可以這麼寫,未來可以塞入更多參數:
      router.push({
        path: "\Home"
      })

       

    3. 回上頁:
      router.go(-1)

       

    4. 儲存網址(下例為開新分頁的函式):
      const openNewTab = (id) => {
        const routeData = router.resolve({ path: `/courses/${id}` });
        window.open(routeData.href, "_blank");
      };

       

    5.  
  4.  

:::

書籍目錄

展開 | 闔起

快速登入


http%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbdsn%3D1750%26tbsn%3D33

計數器

今天: 945945945
昨天: 3068306830683068
總計: 8077450807745080774508077450807745080774508077450