如何在Vue里使用变量进行组件间的通信
使用Vuex的state驱动应用的数据源的方式
1、首先在src目录下新建store目录,且在store目录下新建index.js文件
2、index.js文件下引入并使用vuex,并且定义组件间通信变量,代码如下:
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
/*定义组件间通信变量*/
dayEvents:[],
dayTaskShow:false,
},
mutations: {},
actions: {},
modules: {}
});
3、在main.js里引入store
import store from "./store";
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");
3、使用在store/index.js里定义好的组件通信变量,上述定义好的变量为dayEvents:和dayTaskShow。使用this. s t o r e . s t a t e . d a y E v e n t s 和 t h i s . store.state.dayEvents和this. store.state.dayEvents和this.store.state.dayTaskShow来进行指向。或者在此之前你可以先console.log(this.$store)去查看store里面的东西,在根据内容去找到需要的变量。代码如下:
this.$fetchPost('你的接口',{date:this.date}).then(res=>{
this.$store.state.dayEvents = res.data;
this.$store.state.dayTaskShow = true;
console.log(res.data)
console.log(this.$store.state.dayEvents)
console.log(this.$store)
})
4、在需要使用的组件里js部分进行watch监听,书写位置与methods同级:
watch:{
"$store.state.dayEvents":function (val,old) {
console.log(val)
console.log("监听")
}
},
5、获取到的变量数据就可以跨组件进行通信使用了 代码如下:
<div v-if="$store.state.dayTaskShow" class="list-iteam" v-for="item in $store.state.dayEvents">
<div class="header-list">
<div class="left-tit">
<!--通过接口拿图标-->
<img class="img-box" src=""/>
<span>{{iteam.taskName}}</span>
<span style="margin-left: 10px">{{iteam.taskType}}</span>
</div>
<div class="status-box">
<!--任务状态部分-->
</div>
</div>
<div class="detil">
<!--通过接口获取工作任务下方的详情内容-->
{{item.taskName}}
</div>
</div>
ok