如何从Vue.js中的计算属性更新状态?

时间:2020-10-03 12:40:30

标签: vue.js vuex

我想在名为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)
      },
    },

但是,即使提交按钮,我也无法进行任何更改

反正我能做到吗?谢谢!

1 个答案:

答案 0 :(得分:1)

据我了解,您只是想在键入时进行反跳操作,如果是的话,请使用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>