首页 文章

将数据传递到Vue模板

提问于
浏览
5

我对vue相当新,无法弄清楚如何在模板中添加数据值 . 我正在尝试构建一个非常基本的表单构建器 . 如果我单击一个按钮,它应该将另一个数据数组添加到组件变量中 . 这很有效 . 我正在做一个v-for来添加输入字段,其中一些属性是该组件的数组的一部分 . 我得到它所以它将添加输入但没有值传递到输入 .

我已经创建了一个jsfiddle,我被困在哪里 . https://jsfiddle.net/a9koj9gv/2/

<div id="app">
    <button @click="add_text_input">New Text Input Field</button>
    <my-component v-for="comp in components"></my-component>
    <pre>{{ $data | json }}</pre>
</div>

new Vue({
    el: "#app",

    data: function() {
        return {
            components: [{
                    name: "first_name",
                    showname: "First Name",
                    type: "text",
                    required: "false",
                    fee: "0"
                  }]
            }
    },

    components: {
        'my-component': {
            template: '<div>{{ showname }}: <input v-bind:name="name" v-bind:type="type"></div>',
            props: ['showname', 'type', 'name']
        }

    },

    methods: {
        add_text_input: function() {
            var array = {
                    name: "last_name",
                    showname: "Last Name",
                    type: "text",
                    required: "false",
                    fee: "0"
                  };
            this.components.push(array);
        }
    }
})

我很感激任何帮助,因为我知道我只是遗漏了一些明显的东西 .

谢谢

1 回答

  • 4

    使用props将数据传递到组件中 .

    目前你有 <my-component v-for="comp in components"></my-component> ,它不会将任何道具绑定到组件 .

    相反,做:

    <my-component :showname="comp.showname" 
                  :type="comp.type" 
                  :name="comp.name" 
                  v-for="comp in components"
    ></my-component>
    

    Here is a fork of your fiddle随着变化 .

相关问题