Skip to content

Vue3 路由变化监听与传参

Published: at 04:34 PMSuggest Changes

官方文档

传参

// 这三种形式是等价的
router.push('/users/posva#bio');
router.push({ path: '/users/posva', hash: '#bio' });
router.push({ name: 'users', params: { username: 'posva' }, hash: '#bio' });
// 只改变 hash
router.push({ hash: '#bio' });
// 只改变 query
router.push({ query: { page: '2' } });
// 只改变 param
router.push({ params: { username: 'jolyne' } });

监听

const User = {
  template: '...',
  created() {
    this.$watch(
      () => this.$route.params,
      (toParams, previousParams) => {
        // 对路由变化做出响应...
      }
    );
  },
};

问题及解决方法

  1. 页面跳转传了 params 但是无效

原来的代码

router.push({
  path: '/Car/Appointment',
  params: { address: index },
  query: { address: index },
});

解决方法

params 的时候要传 name

router.push({
  path: '/Car/Appointment',
  params: { address: index },
  query: { address: index },
  name: 'Appointment',
});
  1. 监听不到变化

加入 { immediate: true, deep: true } 就可以了

const route = useRoute();
watch(
  () => route.params,
  () => {
    const { address: getAddress }: any = route.params;
    if (getAddress) {
      address.value = getAddress;
    }
  },
  { immediate: true, deep: true }
);

相关文章

后记

感谢群里 @南京_unbreakable@追寻 的提示和帮助


Previous Post
CSS 解决 border 影响元素宽高的问题 (box-sizing 属性)
Next Post
Stack Overflow 2021 调查报告