首页 > 解决方案 > VueJS 2:无法为输入组件设置双向数据绑定

问题描述

作为 Vue 的新手,当我无法在组件内的输入/选择标签和 Vue 实例内的数据之间建立绑定时,我遇到了这个问题。

示例 #1:

html

<sidebar-select
  :title="UI.sidebar.localeSelect.title"
  :name="UI.sidebar.localeSelect.name"
  :options="UI.sidebar.localeSelect.options"
  :vmodel="selectedLocale">
</sidebar-select>
<sidebar-select
  :title="UI.sidebar.currencySelect.title"
  :name="UI.sidebar.currencySelect.name"
  :options="UI.sidebar.currencySelect.options"
  :vmodel="state.currency">
</sidebar-select>

js - component

Vue.component('sidebar-select', {
  props: ['title', 'name', 'options', 'vmodel'],
  data() {
    return {
      vmodel: this.value
    }
  },
  template: `<div class="col-xs-12 col-md-6" style="padding-left:0;padding-right:30px">
  <div class="cg">
    <label :for="name"><h4>{{ title }}</h4></label>
    <select class="form-control form-horizontal" style="max-width: 300px" 
      :name="name"
      v-model="vmodel">
      <option v-for="option in options" :value="option.value">{{ option.text }}</option>
    </select>
  </div>
</div>`
});

js - data part

var app = new Vue({
  el: '#app',
  data: {
    selectedLocale: 'ru',
    user: {
      'ru': {
        name: 'Саша',
        surname: 'Найдович',
        position: 'программист',
        phone: '1234567',
        email: 'jdlfh@jdlbf.com'
      },
      'en': {
        name: 'Alex',
        surname: 'Naidovich',
        position: 'frontend',
        phone: '1234567',
        email: '1234567@email.eu'
      }
    },
    state: {
      locale: 'ru',
      currency: '€',
      /* *** */
    },
    UI: {
      sidebar: {

        localeSelect: {
          title: 'Язык КП',
          name: 'offer-lang',
          options: [
            {value: 'en', text: 'International - English'},
            /* *** */
            {value: 'ru', text: 'Русский'}
          ],
          preSelected: 'ru',
          stateprop: 'locale'
        },

        currencySelect: {
          title: 'Валюта КП',
          name: 'offer-curr',
          options: [
            {value: '$', text: '$ (Dollar)'},
            {value: '€', text: '€ (Euro)'},
            {value: '₤', text: '₤ (UK Фунт)'},
            {value: '₽', text: '₽ (RUS Рубль)'},
            {value: '', text: 'Ввести вручную'}
          ],
          preSelected: '€',
          stateprop: 'currency'
        },
      } /* etc */
    }
  }
});

我遇到了 2 个错误:[Vue warn]: The data property "vmodel" is already declared as a prop. Use prop default value instead.在初始化和[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "vmodel"尝试更改选择时。我想知道我做错了什么以及这种情况下的最佳实践方法是什么。

更新:主要问题是关于如何在作为参数传递到of 组件v-model时正确使用双向数据绑定。v-modelprops

待更新:明天将添加带有文本输入的示例#2(代码仍在工作中)。

标签: javascriptvue.jsvuejs2

解决方案


推荐阅读