【问题标题】:Vue Object Sync using Component and <Select> Input使用组件和 <Select> 输入的 Vue 对象同步
【发布时间】:2019-07-10 21:15:19
【问题描述】:

我需要使用 &lt;select&gt; 输入在 Vue 中的父组件和子组件之间同步一个对象,但无法获得正确的语法。

组件:

<template>    
  <div>
    <select :value="condition" @change="$emit('update:condition', $event.target.value)">
      <option v-for="variable in variable_options" :value="variable" :key="genUniqueKey(variable)">{{ variable.name }}</option>
    </select>
  </div>
</template>

<script>
  module.exports = {
    props: ['variable_options', 'condition']
  }
</script>

我需要类似标准的 .sync 修饰符,但它似乎不适用于带有对象的选择输入:

<variable-select :variable_options="application_questions" :condition.sync="rule.condition">
</variable-select>

condition 是一个具有idnametype 属性的对象,这些属性来自variable 数组中的variable 对象。我试过做一个initial_condition 道具,然后像文档推荐的那样在select 输入上做一个v-model='selected_condition',但我不知道如何将它与.sync 修饰符一起使用。使用:initial_condition.sync="rule.condition" 是不对的。

有没有办法从子组件中的选定选项传递对象属性,并响应式更新父组件?数据对象的属性是:

rule: {
  condition: {
    id: '',
    name: '',
    type: ''
  }
}

【问题讨论】:

    标签: vue.js vuejs2 vue-component


    【解决方案1】:

    发出&lt;select&gt;

    $event.target.value 指的是HTMLSelectElement.value,它是一个字符串。该对象值将被转换为字符串(返回"[object Object]"),这将阻止.sync 正确更新原始对象。

    一种解决方法是在variable_options[] 属性中使用HTMLSelectElement.selectedIndex

    <select @change="$emit('update:condition', variable_options[$event.target.selectedIndex])">
    

    默认&lt;select&gt;

    默认值是在&lt;option&gt;(不是&lt;select&gt;)上设置的。您可以根据条件的 ID 将 &lt;option&gt;.selected 设置为 true

    <option v-for="variable in variable_options"
            :selected="condition.id === variable.id"
            ...>
    

    demo

    【讨论】:

    • $event.target.selectedOptions[0]._value 会更好,我认为
    • 似乎正在更新父级。但是,任何想法为什么我的初始道具值不会反映在 &lt;select&gt; 输入的初始状态中?它只是默认为列表中的第一个选项。 rule.condition 被发送到 condition 属性,variable_options 中的每个 variable 具有相同的结构,所以我认为它会找到匹配项并在选择中反映该选项?
    • @TravisSmith 默认选择值由&lt;option&gt;.selected(不是&lt;select&gt;.value)设置。
    猜你喜欢
    • 1970-01-01
    • 2019-03-13
    • 2019-12-01
    • 2016-12-18
    • 2020-03-07
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    • 2020-06-08
    相关资源
    最近更新 更多