原文來自:https://blog.csdn.net/wf00334814/article/details/84348654
父子組件間通信常使用props或$emit,對于平行組件之間該方法較麻煩,不利于代碼復用,因此使用this.$store.commit
(1)安裝vuex
(2)可創(chuàng)建一個store文件夾,專門存放相關(guān)文件
(3)新建index.js文件
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store=new Vuex.Store({
state:{
text:{tip:"這是一條數(shù)據(jù)!"}
},
mutations:{//對state進行修改
modify(state,msg){
state.text.tip="修改數(shù)據(jù)!"
}
}
})
(4)掛載到實例上,注冊
import store from '@/store/index.js'
new Vue({
store,
router
}).$mount("#app")
(5)在組件中使用
this.$store.commit('modify',"改變值!")
let value=this.$store.state.text.tip