【问题标题】:VueJS - 'undefined' when using the store to update the stateVueJS - 使用商店更新状态时出现“未定义”
【发布时间】:2017-07-20 08:53:33
【问题描述】:

我在 VueJS 中有一个表单,您可以在其中输入客户信息。输入数据并单击“提交”后,它的作用如下:

  1. 使用axios调用将客户详细信息存储到数据库中的操作

  2. 将结果提交给更新对象的突变

  3. 观察者观察数据的变化,然后更新主 vue 中的对象。

我写的代码是:

动作

addCustomer: function (context, payload) {
   axios.post(`/customers`, {
     customer_name: payload.customer_name,
   }).then(function(message) {
      context.commit("FETCHCUSTOMER", {
        model: message.data.model
   });
});
}

变异

FETCHCUSTOMER: function (state, payload) {
   state.customers.single = payload.model;
},

计算和观察者

customer_created() {
  return this.$store.state.customers.single;
}
// watcher 
customer_created() {
   console.log("Getting here - 1");
   var vm = this;
   vm.customer = this.$store.state.customers.single;
},

然后使用 submit 方法调用它,该方法具有以下内容:

this.$store.dispatch('addCustomer', vm.customer); 
console.log(vm.customer); // LOG 2 

问题是与LOG 2 相关的undefined 在调用Getting here - 1 日志输出之前被调用,这意味着当用户单击提交时,正在创建客户但我需要返回该客户的ID所以我可以在系统中进步。这目前显示为undefined 但是,再次单击该按钮会显示正确的 id..

有没有办法我可以执行以下操作,以便在无需单击提交按钮两次的情况下更新状态?

编辑:

我有以下computed

customer_created() {
  return this.$store.getters.customers.single;
},

我有以下watcher

customer_created: {
   handler: function(val, oldVal) {
       console.log(val);
   },
   deep: true
}

这只是在我重新加载页面时输出undefined,但是当单击调用this.$store.dispatch('addCustomer', vm.customer); 的提交按钮时没有显示任何内容?

【问题讨论】:

  • undefined 问题修复了吗?
  • @KiraSan 是的,这是固定的,非常感谢您的帮助 :)
  • 很好,很乐意提供帮助:)

标签: javascript vuejs2 vuex


【解决方案1】:

尝试使用 Vuex getters

在您的商店对象中,定义它:

getters: {
  customers(state) {
    return state.customers
  }
}

确保您的商店state 包含customers

state: {
  customers: {
    single: null,
  },
  // ...
}

然后在你的组件中computed:

customer_created() {
  return this.$store.getters.customers.single
},

customers() {
  return this.$store.getters.customers
}

你可以这样看:

watch: {
  customers: {
    handler(newCustomers) {
      console.log('Customers changed')
      console.log(newCustomers.single)
    },
    deep: true
  }
}

如果您不想看到客户的强烈反对,也可以这样。

watch: {
  customers(newCustomers) {
    console.log('Customers changed')
    console.log(newCustomers.single)
  }
}

Vuex 吸气剂: https://vuex.vuejs.org/en/getters.html

【讨论】:

  • 感谢您的回复。我感到困惑的一件事是watch handler 来自哪里?你在这里有newCustomers,但我不知道它来自哪里
  • 当你深入观察一个对象时,你需要给你的watcher添加deep标志,所以与其将watcher定义为一个函数,不如将它定义为一个具有处理函数的对象.我认为你的情况并不需要,你可以按照我上面提到的更简单的方式来做。
  • 谢谢。我已经更新了我的问题,你能看看吗? watcher 的公寓一切正常,我不知道为什么
  • 抱歉,submit 现在在watcher 之前被调用了。如果我在视图中输出“{{customer_created}}”,那就没问题了。另外,我将customer_created 的数据传递给ajax,它显示为一个空对象
猜你喜欢
  • 1970-01-01
  • 2020-03-13
  • 1970-01-01
  • 2018-02-16
  • 1970-01-01
  • 2016-06-25
  • 2011-09-13
  • 2012-08-06
  • 1970-01-01
相关资源
最近更新 更多