1.安裝vuex
npm i --save-dev vuex
2.為了方便管理浴讯,在src目錄下新建文件夾store
新建index.js進(jìn)行初始化
新建state.js進(jìn)行數(shù)據(jù)存儲(chǔ)
新建mutations.js保存數(shù)據(jù)修改的方法
3.開(kāi)始編寫(xiě)配置文件
index.js
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'
Vue.use(Vuex)
export default new Vuex.Store({
// 存儲(chǔ)數(shù)據(jù)
state,
// 修改方法
mutations
})
在main.js中引入并實(shí)例化
import store from '@/store/index'
new Vue({
el: '#app',
router,
// 實(shí)例化store
store,
render: h => h(App)
})
4.到這里vuex已經(jīng)配置完成,只要在state.js中寫(xiě)入數(shù)據(jù)即可在項(xiàng)目中引用了
state.js
const state = {
//這里以常用的用戶id為例蔼啦,可以是任意你想保存的數(shù)據(jù)
userId: '0123456789'
}
export default state
5.現(xiàn)在你就可以在項(xiàng)目中的任何組件取到用戶id榆纽,方法如下(關(guān)于map的作用就自己查閱資料吧)
import { mapState } from 'vuex'
export default {
computed: {
...mapState({
userId: state => state.userId
})
},
// 然后在你需要的地方使用this.userId即可,如
created () {
console.log(this.userId)
}
}
6.關(guān)于修改state中屬性的值
還是以用戶id為例捏肢,每個(gè)用戶保存的值必然是不同的奈籽,這個(gè)值需要用mutations中的方法來(lái)修改
mutations.js
const mutations = {
//save_userId是方法名, userId是傳入的修改值
save_userId (state, userId) {
state.userId = userId
}
}
export default mutations
7.在需要保存用戶id的地方調(diào)用mutations中的方法進(jìn)行保存
import { mapMutations } from 'vuex'
export default {
// 引入方法save_userId方法
methods: {
...mapMutations({
save_userId: 'save_userId'
})
}
// 保存或修改數(shù)據(jù)
created () {
this.save_userId('987654321')
}
}
8.到這里數(shù)據(jù)的存儲(chǔ)也完成了,取數(shù)據(jù)只要用第5步的方法即可鸵赫,vuex的簡(jiǎn)單使用也不復(fù)雜衣屏,希望剛?cè)腴T(mén)的小伙伴看完有所收獲吧,之后有空在推出與actions相關(guān)的部分辩棒。
最后編輯于 :2018.06.13 07:01:10
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者