Vue组件传递路由链接跳转失效问题求助
问题原因与解决方法
核心问题1:子组件事件绑定中的插值语法错误
在Vue模板的事件绑定表达式(@click后的代码)里,不需要使用{{}}插值语法。你写的router.push('{{link}}')会把'{{link}}'当成固定字符串,而非读取link属性的值,所以点击后会跳转到{{link}}这个路径(URL编码后就是%7B%7Blink%7D%7D)。
核心问题2:父组件属性传递的引号冗余
父组件里link="'/mainview'"的写法,会让子组件收到的link值是带单引号的字符串'/mainview',而非预期的纯路径/mainview。直接写link="/mainview",Vue会自动解析为字符串;如果要传递JS表达式(比如动态路径),才需要用:(即v-bind:)绑定。
修正后的代码
子组件
<template> <button class="btn" @click="router.push(link)">{{ text }}</button> </template> <script setup lang="ts"> import { defineProps } from 'vue'; import { useRouter } from 'vue-router'; const router = useRouter(); const props = defineProps({ text: String, link: String, }) </script>
父组件(二选一)
方式一:直接传递字符串路径
<Button text="To MainView" link="/mainview"></Button>
方式二:用v-bind绑定(适合动态生成路径的场景)
<Button text="To MainView" :link="'/mainview'"></Button>
内容的提问来源于stack exchange,提问作者pauSei
相关产品推荐
相关产品推荐

