如何在Vue组件之间传递数据

时间:2020-02-28 12:57:27

标签: javascript vue.js components vuex store

这与Vuex以及将数据从一个组件传递到另一个组件有关。我希望将CoreMods.vue中的Module变量传递给ExternalWebpage.vue。更确切地说,可以在外部网页上查看更改。

我的store.js看起来像这样:

    import Vue from 'vue';
    import Vuex from 'vuex';

    Vue.use(Vuex);

    export default new Vuex.store({
        state:{
             CoreModule: ""
      },  
        mutations:{
             update: (state, n) => {
                state.CoreModule = n;
            }
         },

        getters:{
             updated: state =>{
                return state.CoreModule;
                    }
              },

        actions:{
              async createChange({ commit }, n) {
                commit("update", n);
                 }
            }
       });

我有一个CoreMods.vue

    methods:{
        checkModule() {      
          if(!this.completed_cm.includes(this.Module)) {
               if (this.core.includes(this.Module)) {
                  this.completed_cm.push(this.Module);
                  this.$store.dispatch('createChange',this.Module);
  }
}, 

ExternalWebpage.vue

     watch:{
         '$store.state.CoreModule': function(){
              var cm = this.$store.getters.updated;
              if(this.CompletedCore.indexOf(cm) == -1){
              this.CompletedCore.push(cm);
            }
          }
        }

我无法通过将一个组件导入另一个组件来使用道具。这是因为: 1)我不希望将整个组件放置在父组件中。 2)CoreMod是主页上的组件。单击主页上的链接后,它会指向ExternalWebpage。 (这已经使用路由器实现了)

当前此代码不起作用。有人可以帮助您找到解决方案/替代方法。另外,如何将这部分添加到main.js中? 谢谢!!!

1 个答案:

答案 0 :(得分:0)

可能的解决方案是从计算出的值中返回vuex存储值,并观察计算出的值。

computed: {
  coreModule () {
    return this.$store.state.CoreModule;
  }
},
watch:{
  'coreModule': function(){
      var cm = this.$store.getters.updated;
      if(this.CompletedCore.indexOf(cm) == -1){
          this.CompletedCore.push(cm);
      }
  }
}
相关问题