javascript - 如何在 TypeScript 的 Vue Composition API 中响应式访问当前路由名称?

标签 javascript typescript vue.js vue-router vuejs3

如何访问 当前路线名称 , react 性地,与 Vue路由器使用 Vue 组合 API 带有 TypeScript 的 Vue 3 ?

最佳答案

以下是使用 的示例Vue 3.0 Vue 路由器 v4.0.0-beta.12 组合 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 , 对于 组合 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>

关于javascript - 如何在 TypeScript 的 Vue Composition API 中响应式访问当前路由名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63800831/

相关文章:

vue.js - 将索引传递给vuejs中父组件中的子事件监听器

javascript - 在 react 中从数组中删除对象

javascript - 无法自动隐藏更新面板内的标签(div 弹出屏幕)

JavaScript/TypeScript - 对象仅分配可用属性

node.js - 参数类型 "X"不可分配给参数类型 "Y"

javascript - Vue如何给<nuxt-img>添加点击事件

javascript - 根据用户的选择隐藏/显示新菜单

javascript - 如果 margin-left = -3200 则禁用按钮

typescript - Angular2 如何解析导入?

javascript - Vue 模板未在 for 循环中呈现