推送到vuex商店阵列无法在VueJS中运行

Gij*_*ese 15 javascript arrays vue.js vue-resource vuejs2

我正在使用Vuex显示'store.js'的用户列表.那个js文件有这样的数组.

var store = new Vuex.Store({
  state: {
    customers: [
      { id: '1', name: 'user 1',},
    ]
  }
})
Run Code Online (Sandbox Code Playgroud)

我想在同一个数组中插入一组新值

{id:'1',名称:'用户1',}

以上值是从URL(vue-resource)获得的.下面是将获得的数据推送到数组的代码.但是,数据未插入

mounted: function() {
      this.$http.get('http://localhost/facebook-login/api/get_customers.php')
      .then(response => {
        return response.data;
      })
      .then(data => {
        store.state.customers.push(data) // not working!!
        console.log(data) // prints { id: '2', name: 'User 2',}
        store.state.customers.push({ id: '2', name: 'User 2',})
      });
    }
Run Code Online (Sandbox Code Playgroud)

Sau*_*abh 33

您正尝试从vue组件修改vuex状态,但您无法执行此操作.您只能从变异中修改vuex存储

您可以定义如下的突变:

var store = new Vuex.Store({
  state: {
    customers: [
      { id: '1', name: 'user 1',},
    ]
  },
  mutations: {
     addCustomer (state, customer) {
      // mutate state
      state.customers.push(customer)
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

现在您可以从vue实例提交此突变,如下所示:

mounted: function() {
      this.$http.get('http://localhost/facebook-login/api/get_customers.php')
      .then(response => {
        return response.data;
      })
      .then(data => {
        store.commit('addCustomer', { id: '2', name: 'User 2'})
      });
    }
Run Code Online (Sandbox Code Playgroud)

  • @GijoVarghese [docs](https://vuex.vuejs.org/en/mutations.html)中的第一行说:"在Vuex商店中实际改变状态的唯一方法是提交变异." (8认同)
  • @GijoVarghese当您在vue组件中直接修改有状态数据时,vuex的整个目的都会丢失... (8认同)
  • 它可能有效,但属于“未定义行为”类别。这是对框架的滥用,您可以期望一旦开发人员意识到可能存在漏洞,它就会立即停止工作,因为* correct *行为是抛出错误并尝试防止它发生。 (5认同)