我正在寻找一种方法在同一个物体上同时使用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 v-model
指令是v-bind:value
和v-on:input
的语法糖。 This alligator.io article帮助我了解它是如何工作的。
所以基本上你的问题是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>