vue 使用vuex在頁面跳轉的實現(xiàn)方式
vue 使用vuex在頁面跳轉
學習時候碰到的需求場景:我的音樂列表,點擊一個音樂項跳轉到音樂詳情頁
第一種方式:使用 router 動態(tài)路由傳參,將需要的數(shù)據帶過去
音樂列表頁組件:

音樂詳情頁組件:

音樂列表頁通過selectSong方法傳參,在音樂詳情頁的掛載完成里面將數(shù)據賦給songDetail,使其渲染頁面。
第二種方式:使用vuex
下面有補充vuex的相關代碼

音樂詳情組件:

音樂列表頁中通過引入mutations,將點擊的li的數(shù)據提交傳遞到store中的song。在詳情頁中引入getters,獲取store中的song數(shù)據。
這樣在router里面就不需要配置動態(tài)路徑參數(shù),就簡單的字符串。搭配使用vuex也能實現(xiàn)之前動態(tài)路由傳參的效果啦。
在這里記錄下這個簡單vuex操作。也是由于自己對vuex不太熟悉,希望下次需要使用時可以來復習復習。
vuex的相關操作代碼:新建一個store文件,將state,mutations,getters都單獨建文件,在store的index.js中引入。同時要在main.js中將引入store并將其注入到根元素中。
//index.js
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'
import getters from './getters'
Vue.use(Vuex)
export default new Vuex.Store({
state,
mutations,
getters,
})
//state.js
const state = {
song:{}
}
export default state
//mutations.js
const mutations = {
get_song(state,song){
state.song = song
}
}
export default mutations
//getters.js
const getters = {
song: state => state.song
}
export default getters
vuex 頁面跳轉參數(shù)存儲獲取
vue中我們用于頁面跳轉有三種方式
第一種:相當于get請求,參數(shù)會直接帶在地址欄后path+query,path是路由的全路徑。

接收頁面用this.$route.query.feature來獲取
第二種:相當于post請求,參數(shù)不會直接帶在地址欄后name+params

接收頁面用this.$route.params.feature來獲取
第三種:
利用vuex來存儲調轉時頁面的參數(shù),這是因為當我們業(yè)務時頁面跳轉經常會帶很多參數(shù),又要求頁面多開的情況時,只能選擇get方式,因為需要在path后加上匹配id來保證一個頁面根據查詢特征不同而多次打開,可是get請求參數(shù)卻是直接在地址后這樣很不美觀,因此利用vuex來存儲參數(shù),路由只用放上跳轉地址即可:
首先需要
const store = new Vuex.Store({
state: {
parameters:{}//保存頁面?zhèn)鲄?
},
getters:{
parameters : state => state.parameters
},
mutations: {
setParameters : (state,parametersData) => {//頁面參數(shù)傳遞格式{key:‘key',value:‘value'}
if(parametersData){
//試了好久state.parameters[key]=value這樣會報錯只能先取出來添加屬性再賦值
let parameters=state.parameters;
parameters[parametersData.key]=parametersData.value;
state.parameters=parameters;
}
}
},
modules
})
//放置參數(shù)
this.$ store.commit(“setParameters”,{key:‘faceAnalysis'+item.query.feature,value:this.query});
this.$ router.push({path:'/dataSelect/faceAnalysis/'+param.feature,query:{feature:this.query.feature});
接收頁面
let parameters=this.$ store.getters.parameters;
if(this.$ route.query.feature&¶meters[‘faceAnalysis'+this.$route.query.feature]){
var query=parameters[‘faceAnalysis'+this . $route.query.feature];
}
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Maven dependencies與dependencyManagement的區(qū)別詳解
這篇文章主要介紹了Maven dependencies與dependencyManagement的區(qū)別詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-04-04
SpringCloud Zuul在何種情況下使用Hystrix及問題小結
這篇文章主要介紹了SpringCloud Zuul在何種情況下使用Hystrix 及問題小結,感興趣的朋友跟隨小編一起看看吧2018-11-11
Springboot?JPA如何使用distinct返回對象
這篇文章主要介紹了Springboot?JPA如何使用distinct返回對象,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02

