【问题标题】:How to access current route name reactively in Vue Composition API in TypeScript?如何在 TypeScript 的 Vue Composition API 中响应式访问当前路由名称?
【发布时间】:2023-12-16 07:16:01
【问题描述】:

如何通过 Vue 路由器Vue 3 with TypeScript?

【问题讨论】:

    标签: javascript typescript vue.js vue-router vuejs3


    【解决方案1】:

    以下是使用 Vue 3.0Vue Router v4.0.0-beta.12Composition API 语法的示例:

    <script lang="ts">
    import { defineComponent, computed, watch } from 'vue';
    import { useRoute } from 'vue-router';
    
    export default defineComponent({
      name: 'MyCoolComponent',
      setup() {
        const route = useRoute();
        
        console.debug(`current route name on component setup init: ${route.name}`);
    
        // You could use computed property which re-evaluates on route name updates
        // const routeName = computed(() => route.name);
    
        // You can watch the property for triggering some other action on change
        watch(() => route.name, () => {
          console.debug(`MyCoolComponent - watch route.name changed to ${route.name}`);
          // Do something here...
    
        // Optionally you can set immediate: true config for the watcher to run on init
        //}, { immediate: true });
        });
        
        return { route };
      },
    });
    </script>
    
    <template>
      <p>Current route name: {{ route.name }}</p>
    </template>
    

    或者使用当前实验性的脚本设置语法SFC Composition API Syntax Sugar,用于Composition API

    <script setup lang="ts">
    import { computed, watch } from 'vue';
    import { useRoute } from 'vue-router';
    
    export const name = 'MyCoolComponent';
    
    export const route = useRoute();
        
    console.debug(`current route name on component setup init: ${route.name}`);
    
    // You could use computed property which re-evaluates on route name updates
    //export const routeName = computed(() => route.name);
    
    // You can watch the property for triggering some other action on change
    watch(() => route.name, () => {
      console.debug(`MyCoolComponent - watch route.name changed to ${route.name}`);
      // Do something here...
    
      // Optionally you can set immediate: true config for the watcher to run on init
    //}, { immediate: true });
    });
    </script>
    
    <template>
      <p>Current route name: {{ route.name }}</p>
    </template>
    

    【讨论】:

      【解决方案2】:

      这是我的示例,用于查看路线参数。一般搜索如何在Vue 3中查看路由参数时会出现这个问题。

      <script setup lang="ts">
      import axios from 'axios'
      import { ref, onMounted, watch } from 'vue'
      import { useRoute } from 'vue-router'
      
      const route = useRoute()
      const page = ref<any>({})
      
      const fetchPage = async () => {
          console.log('route', route.params)
          const { data } = await axios.get(
              `/api/${route.params.locale}/pages/${route.params.slug}`,
              {
                  params: {
                      include: 'sections,documents,courses',
                  },
              }
          )
      
          page.value = data.data
      }
      
      onMounted(() => {
          fetchPage()
      })
      
      watch(() => route.params.slug, fetchPage)
      </script>
      

      在我的示例中,route.name 不会改变,但 route.params.slug 会改变。

      【讨论】:

      • 我假设路线 name 是自动设置的,但事实并非如此。但是 path 是在 RouteRecordRaw 数组中设置的。所以观看 path 工作。顺便说一句,route.params.slug 运气不好
      • 对不起,slug 是我应用程序中的路由参数。它来自路径/something/:slug等vue-router文件。仔细检查我放置console.log('route', route.params) 的代码。你可以在那里看到你的。注意useRoute 的导入。