【发布时间】:2021-01-18 21:18:35
【问题描述】:
我想在名为 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)
},
},
但是有了这个,即使在提交按钮上我也无法进行任何更改
反正我能做到吗?谢谢!
【问题讨论】:
-
只需将值存储在数据中并在提交点击时执行一个函数,该函数从数据中获取值并发送它。
-
如何从状态中获取数据并将其放入本地数据()?
-
将带有数据道具名称的 v-model 附加到您的输入中。