我在 "http://localhost/question/123/answer/456" 页面中使用vue-router,代码是这么写的:
var author = {
template: "#author",
data: function () {
return {
author: json["answer"]["author"]
}
},
methods: {
getUserLink: getUserLink
},
}
Vue.component("author", author);
var router = new VueRouter({
mode: "history",
routes: [
{
path: "/question/:questionId(\d+)",
components: {
author: author
}
},
{
path: "/question/:questionId(\d+)/answer/:answerId(\d+)",
components: {
author: author
}
}
]
});
new Vue({
router,
el: document.getElementById("root"),
});
HTML代码:
<html>
<head>
<base href="/"/>
</head>
<body>
<div id="root">
<!-- 省略其他html代码 -->
<div class="sidebar">
<router-view name="author"></router-view>
</div>
</div>
<script id="author" type="text/x-template">
<!-- 省略author组件内容 -->
</script>
</body>
</html>
期望的效果是:
在 "http://localhost/question/123/answer/456" 页面会显示author组件,点击某个button,不进行页面跳转,切换到"http://localhost/question/123" ,然后author组件不显示。
可结果是在两个地址下的author组件都不显示了,我猜会不会是路径没有匹配上?
如果不用vue-router,author组件是能正常显示的,说明组件没有问题,
难道只能在 "http://localhost" 页面中使用vue-router,才能匹配path?
刚用vue-router,不怎么会用,求各位大神指点
我找到问题所在了,多个组件用components没有错,单个组件用component,是我的path写错了,正则表达式应该是两个反斜杠:
至于切换路径时隐藏author组件的需求,似乎不能通过vue-router来做,还得用v-if或者v-show