javascript - 推送到 vuex 存储数组在 VueJS 中不起作用

标签 javascript arrays vue.js vuejs2 vue-resource

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

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

我想向同一个数组插入一组新的值

{ id: '1', name: 'user 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',})
      });
    }

最佳答案

你正试图从 vue 组件修改 vuex 状态,你不能这样做。你只能从 mutation 修改 vuex store

您可以像下面这样定义一个突变:

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

现在您可以从 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'})
      });
    }

关于javascript - 推送到 vuex 存储数组在 VueJS 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41830731/

相关文章:

javascript - 检查对象中是否存在某个元素

javascript - 我如何使用 Vue.js 返回值

php - 解析 JSON : multi-level array

arrays - Typescript 参数 - 通用对象数组和对象键数组(部分)

laravel - 如何在 vue 组件上使用 axios 传递上传的文件和传递参数?

vue.js - 仅生产构建错误 : Vuetify Unable to locate target data-app

javascript - 无法正确访问 json github api 响应

javascript - 在平滑传输和颜色变化中调整拨动开关

javascript - Angular JS 与 ASP.NET 母版页

javascript - Div 使用 JavaScript 循环移动