如何在Vue里使用变量进行组件间的通信使用

如何在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.dayEventsthis.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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值