首页 > 解决方案 > 如何从 vuejs 中的计算属性更新状态?

问题描述

我想在一个名为的计算属性中更新我的状态数据,computedFirstName但我遇到了一些问题。

我可以更改状态,但它会随着我输入的每个字母而改变。我不希望仅在单击提交按钮并调用更新方法时才更改它。
这是我的代码

Vuex

export default new Vuex.Store({
  plugins: [vuexLocalStorage.plugin],
  state: {
    APIData: {
      userInfo: {first_name: null},
    },
  },
  mutations: {
    updateFirstName(state, newFirstName) {
      state.APIData.userInfo.first_name = newFirstName;
    },
  },
  getters: {},
  actions: {},
  modules: {},
});

我的组件

<script>
import { mapState } from "vuex";
import { getAPI } from "../../axios-base";
import VueJwtDecode from "vue-jwt-decode";
export default {
  name: "UpdateUserInfoDialog",
  computed: {
    ...mapState(["APIData"]),
    computedFirstName: {
      get() {
        return this.APIData.userInfo.first_name;
      },
      set(newFirstName) {
        this.$store.commit('updateFirstName', newFirstName);
      },
    },
  },
  methods: {
    update: function() {
      var user_id = VueJwtDecode.decode(this.$store.state.accessToken).user_id;
      getAPI
        .patch(
          `/rest/api/users/${user_id}/`,
          {
            first_name: this.computedFirstName,

          },
          {
            headers: {
              Authorization: `Bearer ${this.$store.state.accessToken}`,
            },
          }
        )
        .then(() => {
          this.APIData.userInfo.first_name = this.computedFirstName;
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
</script>

更新
我也试过这样

    computedFirstName: {
      get() {
        return this.APIData.userInfo.first_name;
      },
      set(newFirstName) {
        this.$emit("update:APIData.userInfo.first_name", newFirstName)
      },
    },

但是有了这个,即使在提交按钮上我也无法进行任何更改

反正我能做到吗?谢谢!

标签: vue.jsvuex

解决方案


据我了解,您只需要在键入时进行去抖,如果是这样,请安装 debounce 包npm install debounce并使用以下内容:

<template>
  <input v-model="name" @input="saveDebounced()">
  <button @click="saveName()">Save</button>
</template>

<script>
import { mapState } from "vuex";

export default {
  data: () => ({
    name: ''
  }),
  computed: {
    ...mapState(["APIData"])
  },
  mounted () {
    this.name = this.APIData.userInfo.first_name
  },
  methods: {
    saveName () {
      // update the store and call the API or call an action
      this.$store.commit('updateFirstName', newFirstName)
    },
    // you need an anonymous func here rather than an arrow
    // otherwise you have issues accessing `this`, or you can also
    // try to use this.saveName directly
    saveDebounced: debounce(function () { this.saveName() }, 500)
  }
}
</script>

推荐阅读