vue.js - VueJS:同时使用 v-model 和 :value
问题描述
我正在寻找一种在同一对象上同时使用v-model
和使用的方法。:value
我收到了这个错误:
:value="user.firstName"
v-model
与同一元素发生冲突,因为后者已经在内部扩展为值绑定。
mapGetters
目的是将来自(来自一个商店)的值设置为默认值,并在用户提交修改时设置正确的值。(在onSubmit
)
<div class="form-group m-form__group row">
<label for="example-text-input" class="col-2 col-form-label">
{{ $t("firstname") }}
</label>
<div class="col-7">
<input class="form-control m-input" type="text" v-model="firstname" :value="user.firstName">
</div>
</div>
<script>
import { mapGetters, mapActions } from 'vuex';
export default {
data () {
return {
lang: "",
firstname: ""
}
},
computed: mapGetters([
'user'
]),
methods: {
...mapActions([
'updateUserProfile'
]),
onChangeLanguage () {
this.$i18n.locale = lang;
},
// Function called when user click on the "Save changes" btn
onSubmit () {
console.log('Component(Profile)::onSaveChanges() - called');
const userData = {
firstName: this.firstname
}
console.log('Component(Profile)::onSaveChanges() - called', userData);
//this.updateUserProfile(userData);
},
// Function called when user click on the "Cancel" btn
onCancel () {
console.log('Component(Profile)::onCancel() - called');
this.$router.go(-1);
}
}
}
</script>
解决方案
Vue指令是andv-model
的语法糖。这篇 alligator.io 文章帮助我了解了它的工作原理。v-bind:value
v-on:input
所以基本上你的问题是v-model
指令设置value
为firstname
,而你也明确设置value
为user.firstName
.
有很多方法可以处理这个问题。我认为一个快速而直接的解决方案是firstname
将.v-model
v-bind:value
然后,要将商店中的用户设置为默认用户名,您可以在挂钩中设置fristname
为商店用户的用户名:created
脚本:
<script>
import { mapGetters, mapActions } from 'vuex';
export default {
created() {
this.firstname = this.user.username; // is this right? no used to the map getters syntax, but this is the idea
},
data () {
return {
lang: "",
firstname: ""
}
},
computed: mapGetters([
'user'
]),
methods: {
...mapActions([
'updateUserProfile'
]),
onChangeLanguage () {
this.$i18n.locale = lang;
},
// Function called when user click on the "Save changes" btn
onSubmit () {
console.log('Component(Profile)::onSaveChanges() - called');
const userData = {
firstName: this.firstname
}
console.log('Component(Profile)::onSaveChanges() - called', userData);
//this.updateUserProfile(userData);
},
// Function called when user click on the "Cancel" btn
onCancel () {
console.log('Component(Profile)::onCancel() - called');
this.$router.go(-1);
}
}
}
</script>
推荐阅读
- c# - 在 SQL 语句中使用 ComboBox 选择
- javascript - 通过类名的一部分查找类
- python - 如何在 SocketCAN 或 Python-can 中发送和接收文件?
- ios - 如何在不重新下载的情况下将设备 ID 添加到临时临时配置文件?
- java - 使用第一行文本值java获取第二行xml
- css - 使用 sass 悬停时未显示图标
- javascript - 有条件地将道具传递给组件
- mysql - 如何检查从 GROUP 生成的记录集中是否存在非字符串值?
- android - 更改构建工具和 gradle 配置后在 ImageView 上像素化的矢量图像?
- php - 为什么当胡说八道附加到URL时,PHP-Pages的URL不会产生404