【问题标题】:Select Component Vue JS - Default Select Value选择组件 Vue JS - 默认选择值
【发布时间】:2017-03-11 16:29:44
【问题描述】:

我是 vue.js 的新手,并试图为我的选择框创建一个组件。我很难通过父组件将默认值传递给选择。

现在我在父组件中有这个

<div class="row">
  <div class="col-md-4">
    <active-dropdown :selected='selected', :options = 'active_options', @update = 'update_selected'></active>
  </div>
</div>

这里是下拉组件

Vue.component 'active-dropdown',
  template: '#active-dropdown'

  props: ['options', 'selected']

  data: ->
    selection: { active_eq: 1, text: 'Active', show: true }

  methods:
    notify_selection: ->
      @.$emit('update', @.selection)

这是模板

<script id="active-dropdown" type="text/template">
  <div class="form-group">
    <label>Active</label>
    <select class="form-control" v-model="selection" v-on:change="notify_selection">
      <option v-bind:value="{ active_eq: option.value, text: option.text, show: true }" v-for="option in options">{{ option.text }}</option>
    </select>
  </div>
</script>

当我尝试使用 selected 的 props 作为选择模型时,vue 会警告我不能改变 props。我应该如何在不将模型更改为所选道具的情况下为选择设置默认值?

【问题讨论】:

    标签: javascript components vue.js


    【解决方案1】:

    欢迎来到 SO!

    Vue 不希望您直接修改 prop,而是将它们传递给数据(或使用计算值)并修改该值,您可以在 created 钩子中执行此操作:

    props: ['selected','options'],
    created(){
      this.selectedOption = this.selected;
    },
    data(){
      return {
        selectedOption: ''
      }
    }
    

    然后你可以将你的选择框绑定到那个:

    <select v-model="selectedOption">...</select>
    

    我创建了一个简化的小提琴来向您展示它是如何工作的:

    https://jsfiddle.net/6h8gam1c/

    【讨论】:

      猜你喜欢
      • 2020-09-21
      • 1970-01-01
      • 2016-02-20
      • 2016-07-07
      • 2022-06-22
      • 1970-01-01
      • 1970-01-01
      • 2017-01-29
      • 2022-07-21
      相关资源
      最近更新 更多