需求分析:首頁面有兩個組件,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。