Moi*_*Pio 10 javascript routing vue.js
我想在Vue.js应用程序中为不同的路由使用相同的组件.
我目前有这样的事情:
main.js
const routes = [
{ path: '/route-1', name: 'route-1', component: MyComponent },
{ path: '/route-2', name: 'route-2', component: MyComponent },
{ path: '/route-3', name: 'route-3', component: MyComponent },
]
const router = new VueRouter({
routes
})
Run Code Online (Sandbox Code Playgroud)
myComponent.vue
<ul>
<li><router-link to="/route-1">Route 1</router-link></li>
<li><router-link to="/route-2">Route 2</router-link></li>
<li><router-link to="/route-3">Route 3</router-link></li>
</ul>
Run Code Online (Sandbox Code Playgroud)
当我在浏览器中手动键入路由时,一切都运行良好,但是当我尝试使用这些路由器生成的链接之一在路由之间导航时,没有任何反应.路线改变但内容仍然相同.知道如何解决这个问题吗?
谢谢!
mzg*_*ner 24
这是预期的行为,因为Vue试图获得最佳并重用现有组件.您想要实现的行为过去通过调用的设置来解决canReuse,但已被弃用.目前推荐的解决方案是:key在您的<router-view>喜欢上设置一个独特的属性:
<router-view :key="$route.path"></router-view>
Run Code Online (Sandbox Code Playgroud)
看看这个JSFiddle示例.
您可以使用watch属性,因此您的组件不会浪费时间重新加载:
index.js 你可能有这样的东西
const routes = [
{
path: '/users/:id',
component: Vue.component('user', require('./comp/user.vue').default)
}
]
Run Code Online (Sandbox Code Playgroud)
用户.vue
created(){
// will fire on component first init
this.init_component();
},
watch: {
// will fire on route changes
//'$route.params.id': function(val, oldVal){ // Same
'$route.path': function(val, oldVal){
console.log(this.$route.params.id);
this.init_component();
}
},
methods: {
init_component: function(){
// do anything you need
this.load_user_data_with_ajax();
},
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5229 次 |
| 最近记录: |