4

如何在 vue.js 中选择选项。React 有类似的东西this.props.children,我用它来处理这种情况。如何在 vue.js 中解决这个问题?

我还尝试使用 $children 访问孩子,但它始终是一个空数组。

在此示例中,选择框没有选项。在 jsFiddle 上也添加了示例:https ://jsfiddle.net/kt8urx7d/

var FormComp = Vue.extend({
    template: '#form-comp'
});
Vue.component('form-comp', FormComp);

var SelectField = Vue.extend({
    template: '#select-field'
});
Vue.component('select-field', SelectField);

var SelectFieldOption = Vue.extend({
    template: '#select-field-option'
});
Vue.component('select-field-option', SelectFieldOption);


new Vue({
  el: '#container',
  template: '<form-comp></form-comp>'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>

<script type="x/template" id="form-comp">
	<form>
  	<h1>This is my Form</h1>
  	<select-field name="my-select-field">
    	<select-field-option value="my-value-1">My Text 1</select-field-option>
      <select-field-option value="my-value-2">My Text 2</select-field-option>
    </select-field>
  </form>
</script>

<script type="x/template" id="select-field">
	<select name="{{ name }}">
  	<!-- include children: select-field-option -->
  </select>
</script>

<script type="x/template" id="select-field-option">
	<option value="{{ value }}">{{ content }}</option>
</script>

<div id="container"></div>

4

1 回答 1

0

在组件模板中呈现元素的方式存在一些问题。看看这个:https ://vuejs.org/guide/components.html#Content-Distribution-with-Slots

另一方面,Vue 使用浏览器的HTML渲染系统,这意味着“应该”在 HTML 元素中的元素会被丢弃。例如,Vue期待optioninside select,而不是select-field-option。要克服此限制,您可以执行以下操作:

<option is="select-field-option" value="lalala"></option>

重新考虑您在组件内使用模板的方式。这可能对起步很有用:https ://jsfiddle.net/kt8urx7d/5/

于 2016-08-16T23:31:26.513 回答