引子
最近更新博客时需要在导航栏里增加一个分类的列表,但是分类的路由是同一个路由,只是后面的
参数id
不同,点击切换不同的列表时,发现URL正常了,但不是我想要的结果。因为就算路由发生了变化,数据还是没有变化,因为调用的依然是同一个组件,组件复用了所以不刷新。
解决方法
因为vue每次调用组件的时候会观察是否已经created
,而我的组件是已经created的,所以当我id发生变化的时候,组件没有重新创建。因此要在组件中再加上一个方法。具体代码如下:
导航组件
<ul class="dropdown-menu">
<li v-for="item in series_list" :key="item.series_name">
<router-link :to="/series/+item.id">{{item.series_name}}</router-link>
</li>
</ul>
点击分类结果组件
export default{
beforeRouteUpdate (to, from, next) {
//next方法使URL显示正常
next()
//数据改变的方法(此处为自定义的数据改变方法)
this.getSeries(to.params.id)
},
mounted () {
this.getSeries(this.id)
},
methods: {
//自定义的数据改变方法
getSeries (id) {
this.$http.get(global.domain + this.url + id).then(res => {
this.blogList = res.data.essay_series
this.series_blog = this.blogList
this.series_title = res.data.series_name
}, res => {
this.$router.push({path: '/error'})
})
}
}
}