vue.js - 如何从 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)
},
},
但是有了这个,即使在提交按钮上我也无法进行任何更改
反正我能做到吗?谢谢!
解决方案
据我了解,您只需要在键入时进行去抖,如果是这样,请安装 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>
推荐阅读
- swift - 性能:Array.removeAll vs `= []`
- mysql - 来自设计的 SQL 音乐播放列表数据库查询
- php - 尝试启动 docker 容器时出错
- java - 为什么事件循环使用多个线程?
- python - 在 Python 中创建表格时如何简化表格
- asp.net-mvc - 如何在我的 Asp.net MVC 应用程序会话管理中维护 Id 值
- git - 已删除 git clone [https] 创建的本地存储库,现在 git clone [https] 将不起作用
- python - PyGitHub:无法访问我团队的私有存储库
- php - 使用 Ajax 在 wordpress admin 中使用 FPDF 生成 PDF
- excel - 如何在 Internet Explorer 弹出窗口上按保存?