需求分析:首頁面有两个组件,Artist组件和Tag组件,分别对应文章组件和标签组件,点击Tag组件的某项标签,要动态更新Artist组件里的内容,并且路由要传递查询信息
首先,要根据Tag组件选中的tid去动态更新articles数据,如何去实现呢?
这时候我想到的方法:是把articles数据放在vuex上实现组件共享,点击标签后,Tag组件直接异步请求articles数据,并更新Vuex上的articles,然后再更新路由,同时设置Article组件的articles为Computed属性,这样就可以动态更新页面数据了
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store=new Vuex.Store({
/*为什么共享文章:因为方便tag页面操作文章,点击不同tag,更新不同文章*/
state:{
articles:{
artContent:[],
total:0,
},
},
mutations:{
initArticles(state,obj){
state.articles.artContent=obj.data;
state.articles.total=obj.total;
}
},
})
export default store
Article.vue
import store from "@/store";
export default {
name: "Article",
data() {
return {
currentPage:1,
}
},
computed:{
articles(){
return store.state.articles
}
},
mounted(){
this.initAllArticles()
}
},
methods: {
initAllArticles() {
this.getRequest('/home/getallarticles?pageId='+this.currentPage).then(resp => {
if (resp) {
store.commit("initArticles",resp)
}
})
},
Tag.vue
getArticlesByTag(tid,tagName)
{
this.getRequest('/home/getArticleByTag?tId='+tid+'&pageId='+1).then(resp => {
if (resp) {
store.commit("initArticles",resp)
}
})
this.$router.push({path:"/home/getArticleByTag",query:{tid:tid,tagName:tagName}})
}
问题:
这样做会带来两个问题:
一:路由传递的信息没有充分利用
二:页面后退后,文章列表更新不回全部文章,因为你点击分类文章,更新了Vuex里的articles数据,回退后,Article组件由始至终没有被重新挂载,在mounted里定义的数据请求方法调用不了,自然数据也更新不了。
解决方法:所以要对路由进行监听,充分利用路由里传递的数据
添加watch属性,监听路由
watch:{
$route(to,from){
if(to.path=='/home')
this.initAllArticles()
if(to.path=='/home/getArticleByTag')
this.initTagArticles()
}
},
这样路由前进后退,都会进行不同的数据请求方法来重新获得各自的数据,
如果路由为/home,请求全部文章,如果为/home/getArticleByTag则请求分类文章(实际不必如此分开两个方法进行请求,可以为一个请求然后根据传递的参数进行sql查询,在后端进行兼容就行了,这里只是为了方便理解)
并且Tag组件不用再进行数据请求,统一由Atricle组件自己更新自己的数据,也不必再把articles数据存入Vuex。