VueJS - 'undefined' 使用商店更新状态时

VueJS - 'undefined' when using the store to update the state

我在 VueJS 中有一个表单,您可以在其中输入客户信息。输入数据并单击 'Submit' 后,它会执行以下操作:

  1. 使用 axios

  2. 调用将客户详细信息存储到数据库中的操作
  3. 将结果提交给更新对象的突变

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

我写的代码是:

Action

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

Mutation

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

Computed & watcher

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 日志输出之前被调用,这意味着当用户单击提交时,正在创建客户,但我需要 return 该客户的 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); 的提交按钮时没有任何显示?

尝试使用 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