【问题标题】:Vue.js - Reactivity of a select whose value is the selected object and not its idVue.js - 选择的反应性,其值为所选对象而不是其 id
【发布时间】:2017-06-20 19:42:02
【问题描述】:

我正在使用vue.js 2.3element-ui。我正面临一个选择下拉列表的反应性问题,其值为item 选择。

问题

select 不会自动填充初始对象value

注意事项

如果我将:value="item" 更改为:value="item.name"

form: {option: {name:'blue', price: ''}}form: {option:'blue'}

它正在工作

问题

select dropdown 的值只是stringid 而是整个被选中的对象时,有没有办法让select dropdown 完全响应

https://jsfiddle.net/LeoCoco/aqduobop/

<

div style='margin-bottom:50px;'>
My form object : 
  {{form}}
</div>

  <el-button @click="autoFill">Auto fill</el-button>

  <el-select v-model="form.option" placeholder="Select">
    <el-option v-for="item in options" :key="item.name" :label="item.name" :value="item">
    </el-option>
  </el-select>
</div>


    var Main = {
    data() {
      const options = [
     {name: 'blue', price: '100$'},{name: 'red', price: '150$'},
      ]

      return {
        currentItem: 0,
        options,
        form: {
            option: {name:'', price: ''},
        },
         testForm: {
            option:{name:'red', price: '150$'}
        },
      }
    },
    methods: {
      autoFill() {
        this.form =  Object.assign({}, this.testForm); // -> Does not work
      }
    }
  }
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')

【问题讨论】:

  • 您的选项总是硬编码还是来自某个地方?
  • 默认情况下,form 对象应为空。在AJAX 调用之后检索选项。 testForm 也在 AJAX 之后检索以使用 autofill 函数预填充下拉列表

标签: vuejs2


【解决方案1】:

您的问题是,当所选值是一个对象时,form.option需要是相同的 em>对象,以便在选择列表中选择它。

例如,如果我将小提琴代码更改为 this,我认为它会按照您的预期工作。

var Main = {
    data() {
      const options = {
        'color': [{name: 'blue', price: '100$'},{name: 'red', price: '150$'}],
        'engine': [{name: '300hp', price: '700$'},{name: '600hp', price: '2000$'}],
      }
      let currentCategory = 'color'

      return {
        currentCategory,
        currentItem: 0,
        options,
        form: {
            option: options[currentCategory][0]
        },
         testForm: {
            option:{name:'blue', price: '100$'}
        },
      }
    },
    methods: {
      autoFill() {
        this.form =  Object.assign({}, this.testForm); // -> Does not work
      }
    }
  }
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')

这是你的小提琴updated

您说您的值来自 ajax 调用。这意味着当您设置form.option 时,您需要将其设置为options[currentCategory] 中的对象之一。

【讨论】:

  • 如果你点击autofill它不起作用jsfiddle.net/LeoCoco/p8rusa82。想象一下,检索选项需要 10 分钟。是否可以使用本地对象 testForm 预填充下拉列表而不引用 options
  • 可以不做options[0] 而是做` {name: 'blue', price: '100$'}`
  • 自动填充不起作用,因为它是一个不同的对象。即使它具有相同的属性。
  • 你的意思是没有办法用具有相同属性的不同对象预填充下拉列表?然而,当我点击autofill form 对象时,链接到select 的对象发生了变化
  • @Leo 您想在选择选项之前显示选项吗?
猜你喜欢
  • 2017-07-22
  • 1970-01-01
  • 2013-05-29
  • 1970-01-01
  • 2021-01-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多