【问题标题】:How do I export a string to another Vue file?如何将字符串导出到另一个 Vue 文件?
【发布时间】:2018-07-12 14:26:40
【问题描述】:

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

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

payload 将存储所有行,payload[0] 保存列标题名称的值。这段代码的输出是这样的:

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

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

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

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

【问题讨论】:

  • 你使用的是单文件组件吗?
  • 是的,我使用的是单文件组件。

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


【解决方案1】:

如果您尝试从组件内访问存储中的数据,那么您可能只想将状态映射到组件或将 getter 映射到组件。组件(或操作)使用突变来修改存储的状态。所以你会做类似的事情......

//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>

【讨论】:

    【解决方案2】:

    这是您在单个文件组件中导入内容的方式。

    <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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-08
      • 1970-01-01
      • 2012-03-02
      • 1970-01-01
      • 1970-01-01
      • 2013-08-12
      • 2021-02-17
      • 2014-02-13
      相关资源
      最近更新 更多