首页 > 解决方案 > 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.jsvuejs2v-model

解决方案


Vue指令是andv-model的语法糖。这篇 alligator.io 文章帮助我了解了它的工作原理。v-bind:valuev-on:input

所以基本上你的问题是v-model指令设置valuefirstname,而你也明确设置valueuser.firstName.

有很多方法可以处理这个问题。我认为一个快速而直接的解决方案是firstname将.v-modelv-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>

推荐阅读