Vue3使用路由跳转的坑

技术栈:Vue3+Vite 3+Vant 3

错误的写法:
const router = useRouter();写在方法里

<script setup lang="ts">
import { useRouter } from 'vue-router';

const onClickLeft = () => alert('左');
const onClickRight = () => { 
  const router = useRouter()
  router.push({path: '/search'})
};
</script>

会报错误:
Vue3使用路由跳转的坑_第1张图片

正确的写法:

<script setup lang="ts">
import { useRouter } from 'vue-router';

const router = useRouter();

const onClickLeft = () => alert('左');
const onClickRight = () => { 
  //切记不可将router定义在方法中,这样他不是响应式数据,会报错
  // const router = useRouter()
  router.push('/search');
};
</script>

<template>
  <van-nav-bar 
    title="标题" 
    left-text="返回" 
    left-arrow
    @click-left="onClickLeft"
    @click-right="onClickRight">
    <template #right>
      <van-icon name="search" size="18" />
    </template>
  </van-nav-bar>
  <div id="content">
    <router-view/>
  </div>
</template>

<style scoped>
</style>

学习vue3的链接

你可能感兴趣的:(vue,vue.js,前端)