VueJS:同时使用 v-model 和 :value

waw*_*los 6 vue.js vuejs2 v-model

我正在寻找一种在同一对象上同时使用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>
Run Code Online (Sandbox Code Playgroud)

Yom*_* S. 3

v-model通常,您希望在对象本身上设置 的“初始”值,例如:

data() {
  return {
    firstname: 'someName'
  }
}
Run Code Online (Sandbox Code Playgroud)

但由于您是从商店获取它的,因此您可以使用 访问特定的 getter 对象this.$store.getters[your_object],因此我将删除:value绑定并v-model单独使用:

<div class="col-7">
  <input class="form-control m-input" type="text" v-model="firstname">
</div>
Run Code Online (Sandbox Code Playgroud)
<script>
export default {
  data() {
    return {
      lang: "",

      firstname: this.$store.getters.user.firstName
    }
  },

  // ...
}
</script>
Run Code Online (Sandbox Code Playgroud)