需求:在首頁(index.vue)調用了組件A(componentA.vue),和組件B(componentB.vue),想通過主鍵B的點擊事件,觸發組件A的事件
步驟:
1.先安裝vuex,執行 npm install vuex --save代碼,安裝vuex
2.在main.js文件中導入vuex,代碼如下:
import Vue from 'vue' import App from './App' import router from './router' import vuex from 'vuex' Vue.config.productionTip = false Vue.use(vuex) /* eslint-disable no-new */ new Vue({ el: '#app', router, components: { App }, template: '<App/>' })
3.在根目錄下創建文件夾:vuex,然后添加store.js文件,store.js文件代碼如下:
import vue from 'vue' import Vuex from 'vuex' vue.use(Vuex) const state={ count:1 } const mutations={ add(state){ state.count++; } } export default new Vuex.Store({ state,mutations })
4.在index.vue中引用A組件和B組件,代碼如下:
<template>
<div>
<h1>組件A調用</h1>
<compontentA></compontentA>
<h1>組件B調用</h1>
<compontentB></compontentB>
</div>
</template>
<script>
import compontentA from './componentA'
import compontentB from './componentB'
export default {
data() {
return {
msg: "Welcome to Your Vue.js App"
};
},
components:{
compontentA,
compontentB
}
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1,
h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
5.組件A代碼:
<template>
<div>
<h1>我是組件A</h1>
{{$store.state.count}}
</div>
</template>
<script>
import store from '@/vuex/store'
export default {
data(){
return{
result:0
}
},
created(){
},
store,
methods:{
watchstore(){
alert("從B組件觸發A組件");
}
},
watch:{
'$store.state.count':function(val){
this.watchstore(); }
}
}
</script>
<style scoped>
</style>
描紅部分注意,監聽狀態的方式和監聽其他變量和方法的方式有點不一樣,代碼:
'$store.state.count':function(val){
this.watchstore();
}
6.組件B代碼如下:
<template>
<div>
<h1>我是組件b,利用組件b的事件,控制狀態,達到修改組件A的目的</h1>
<button @click="$store.commit('add')">操作狀態+1</button>
</div>
</template>
<script>
import store from '@/vuex/store'
export default {
store,
methods:{
}
}
</script>
<style scoped>
</style>
以上步驟就可以達到使用組件B的點擊事件控制組件A的內部方法的效果,vuex的細節應用,我們下次具體討論,本次關鍵點在於A組件的監聽。
