如何将字符串导出到另一个Vue文件?

时间:2018-07-12 14:26:41

标签: javascript vue.js vuejs2 vue-component vuex

我有一个masterData.js文件,该文件存储我的主数据,简而言之,该文件读取我的mongo db数据并将其发送到其他项目组件。我创建了一个函数,将masterData.js文件中的字符串导出为:

/ ***************************** MUTATIONS
const mutations = {
exportColumns (payload) {
  Object.keys(payload[0]).map(x => { return x; });
 }
}

有效负载将存储所有行的位置,有效负载[0]保留列标题名称的值。此代码块的输出如下:

["_id","businessAreaName","businessAreaDisplay","councilDisplay","councilID"]

我想将值传输到masterData.vue文件。我在masterData.Vue上的代码是:

importColumns () 
  {
  let payload = {
    vm: this,
    mutation: 'masterData/exportColumns'
  };
}

我还应该添加些什么来检查是否接收到列名?

2 个答案:

答案 0 :(得分:1)

如果您试图从组件内部访问商店中的数据,那么您将希望仅将状态映射到组件或将吸气剂映射到组件。组件(或操作)使用变异来修改存储的状态。因此,相反,您会做类似...

//masterData.js
//assuming this gets rolled up as a module called masterdata to the primary store
//store for payload state
const state = {
  payload: null,
}

//allows payload to be set -- not sure how you are retrieving the payload but you can use this to store it however you get it
const mutations = {
  setPayload (state, payload) {
    state.payload = payload
  }
}

//get just the columns
const getters = {
  getColumns (state) {
    Object.keys(state.payload[0]).map(x => { return x; })
  }
}

export default {
  state,
  mutations,
  getters,
}

然后

//masterData.vue
<template>
  //...
</template>

<script>
  import { mapGetters, mapState } from 'vuex'

  export default {
    computed: {
      //I believe getting state from a store module requires a function like this
      ...mapState({
        payload: function(state) {
          return state.masterdata.payload
        },
      }),
      //I think for getters you can just reference the method and it will find it
      ...mapGetters([
        'getColumns',
      ])
    },
  }
</script>

答案 1 :(得分:0)

这是将内容导入单个文件组件的方式。

<template>
  <!-- html stuff -->
</template>
<script>
import Mutations from 'yourModule.js'

export default {
  name: 'YourComponent',
  props: {},
  data(){
    return {
      foo: 'foo'  
    }
  },
  methods{
    mymethod() { 
      Mutations.exportColumn(this.foo); 
    },
  }
}
</script>