vue.js - 将数据传递到 Vue 模板

标签 vue.js

我是 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);
        }
    }
})

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

谢谢

最佳答案

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

目前你有<my-component v-for="comp in components"></my-component> ,它不会将任何 Prop 绑定(bind)到组件。

相反,做:

<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随着变化。

关于vue.js - 将数据传递到 Vue 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38275155/

相关文章:

vue.js - 有没有办法添加或删除整个属性?

php - laravel 5.4 Vue 组件不工作

javascript - 数据过滤 Javascript(嵌套字典和数组)

Vue.js 通过 httpVueLoader 传递数据

javascript - 为什么 vue-property-decorator @Emit 在 Vue TypeScript 文件中不起作用?

import - 如何避免 VueJS 中重复的导入和组件声明

javascript - Vue 3 - inject() 只能在 setup() 或功能组件内部使用

javascript - 了解 Element UI 事件处理程序触发 RangeError : Maximum call stack size exceeded? 的原因

javascript - 如何在vue即时搜索中创建自定义细化列表?

javascript - Vue.js - 在点击事件上添加类