Vue路由传参如何指定params参数可传可不穿?

348 阅读1分钟

配置路由的时候,占位了(params参数),但是路由跳转的时候不传递。 路径会出现问题

配置路由:

        {
            path:"/search/:keyword",
            component:Search,
            name:'search'
        }
<form>
    <input type="text" v-model="keyword" />
    <button type="button" @click="goSearch">搜索</button>
</form>
methods:{
            goSearch(){
                this.$router.push({
                    name:'search',
                    //没传params参数
                    query:{k:this.keyword}
                })
            }
        }

运行结果:

image.png

image.png

image.png

发现路径有问题 应该为:localhost:8080/#/search?k=qwe

解决办法: 在配置路由的时候,在占位的后面加上一个?

        {
            path:"/search/:keyword?",
            component:Search,
            name:'search'
        }

image.png