vue.js - Vuex:防止输入字段更新状态/存储
问题描述
在我的 Vuex 应用程序中,我有一个update
表单,它使用用户凭据(来自 Vuex 商店)预先填充输入字段,然后在提交时将表单提交到数据源。
因此,我需要在页面上显示用户详细信息,但不希望在用户更改表单中的值时(反应性地)更新它们,因为在我的情况下,如果用户未完成表单,则会产生误导离开页面并返回。然后看起来数据已更新(尚未提交,因为他们尚未提交表单)。
这是我的代码片段:
表格(HTML):
<input
v-model.trim="userProfile.name"
:value="userProfile.name"
type="text" >
</input>
<input
v-model.trim="userProfile.position"
:value="userProfile.position"
type="text" >
</input>
<div>
{{ userProfile.name }} {{ userProfile.position }}
</div>
和 Vue 代码:
computed: {
...mapState(["userProfile"]),
},
methods: {
updateProfile() {
this.$store.dispatch("updateProfile", {
name: this.name !== "" ? this.name : this.userProfile.name,
position: this.position !== "" ? this.position : this.userProfile.position,
})
}
},
只是为了澄清这段代码可以正常工作,对我来说,问题是我不希望它{{ userProfile.name }}
{{ userProfile.position }}
是被动的,只有在提交表单后才更新。
解决方案
答案是使用存储中的值初始化您的初始数据。
export default {
...
data() {
const localUserProfile = JSON.parse(JSON.stringify(this.store.state.userProfile))
return {
localUserProfile
}
},
...
}
<input
v-model.trim="localUserProfile.name"
type="text" >
</input>
<input
v-model.trim="localUserProfile.position"
type="text" >
</input>
<div>
{{ userProfile.name }} {{ userProfile.position }}
</div>
注意:你应该创建你的独立副本store.state.userProfile
,这样做你可以使用JSON.parse(JSON.stringify(this.store.state.userProfile))
或lodash.clonedeep
。
不要忘记使用localUserProfile
您updateProfile
方法中的值更新您的商店。
您的代码也有一些错误:
- 您不能直接使用
v-model="userProfile.name"
. 可能您的控制台中有错误。
推荐阅读
- flutter -
- java - 如何有效地找到单个像素值随时间变化的标准偏差?(来自视频源)
- php - 如何使用 PHP curl 发布 $_FILES?
- php - 尝试使用formdata上传图像并在reactnative中获取api但是当尝试在php文件中打印formdata时没有图像数据是为什么?
- sanity - 为什么在 Sanity.IO 中没有正确准备渲染
- arrays - 如何将数组传入和传出函数?
- java - 如何画一个光滑的椭圆?
- r - 使用 ggplot2 有条件地为条形图分配 geom_text 位置
- clockify - 用户状态 API
- r - 如何使用 R 从菜单选项卡中具有类似“#”url 的网站抓取数据?