【问题标题】:How to edit the template depending on what data there is?如何根据有哪些数据来编辑模板?
【发布时间】:2019-02-16 16:16:03
【问题描述】:

我有一个 Vue 组件,它使用<option>s 创建一个<select>。我希望选择中的选项依赖于列表。

Vue.component('column-header', {
    data: function() {
         return {
           options: ['Name', 'Address', 'Email', 'Mobile', 'Card Number', 'Other'],
         }
    },
    template: `<div class="uk-width-1-5">
                <select class="uk-select">
                    {{ options }}
                </select>
            </div>`
});

new Vue({ el: '#app' })

当我决定稍后扩展我的选项列表时,它应该会自动插入新项目作为选项。这是正确的做法吗?

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component


    【解决方案1】:

    使用v-for 渲染元素列表:

    <option v-for="option in options">{{option}}</option>
    

    options 数据属性是响应式的,因此向该数组添加项目会自动更新模板以在 &lt;select&gt; 中包含新的 &lt;option&gt;

    Vue.component('column-header', {
        data: function() {
             return  {
               options: ['Name', 'Address', 'Email', 'Mobile', 'Card Number', 'Other'],
             }
        },
        template: `<div class="uk-width-1-5">
                    <select class="uk-select">
                        <option v-for="option in options">{{option}}</option>
                    </select>
                    <button @click="addOption">Add option</button>
                </div>
                `,
      methods: {
        addOption() {
          this.options.push('Foo' + this.options.length);
        }
      }
    });
    
    new Vue({ el: '#app' })
    <script src="https://unpkg.com/vue@2.6.6"></script>
    
    <div id="app">
      <column-header></column-header>
    </div>

    【讨论】:

      【解决方案2】:

      您可以使用v-for 遍历数组并创建新选项。

      <select>
      <option v-for="option in options" :key="option">{{ option }}</option>
      </select>
      

      【讨论】:

        猜你喜欢
        • 2013-11-27
        • 1970-01-01
        • 1970-01-01
        • 2018-05-25
        • 1970-01-01
        • 2010-09-17
        • 1970-01-01
        相关资源
        最近更新 更多