道具值不在vuejs中呈现

时间:2016-10-29 10:03:11

标签: javascript laravel laravel-5.3 vue-component vue.js

我正在尝试在Laravel 5.3应用程序的vuejs中创建一个ajax表单组件。但是,我想,我一直在显示表单字段。有人可以帮帮我吗?

呈现表单的前端:

<ajax-form
    :autocomplete=false
    :schema="[{
        label: 'Username:',
        type: 'text',
        id: 'username',
        name: 'username',
        placeholder: 'Eg. johndoe',
        inputClass: 'input is-info',
        model: 'username',
        required: true,
    }, {
        label: 'Email:',
        type: 'email',
        id: 'email',
        name: 'email',
        placeholder: 'Eg. johndoe@example.com',
        inputClass: 'input is-info',
        model: 'email',
        required: true,
    }, {
        label: 'Password',
        type: 'password',
        id: 'password',
        name: 'password',
        placeholder: 'Eg. password',
        inputClass: 'input is-info',
        model: 'password',
        required: true,
    }, {
        label: 'Confirm Password',
        type: 'password',
        id: 'confirm_password',
        name: 'confirm_password',
        placeholder: 'Eg. password',
        inputClass: 'input is-info',
        model: 'confirm_password',
        required: true,
    }]"
></ajax-form>

AjaxForm.vue文件中的template

<form method="POST">
    <div v-for="field in schema">
        <label class="label">{{ field.label }}</label>
        <p class="control">
            <input
                type="field.type"
                name="field.name"
                id="field.id"
                class="field.inputClass"
                placeholder="field.placeholder"
                required="field.required"
                v-model="field.model"
            >
        </p>
    </div>
</form>

script标记的内容:

<script>
    export default {
        props: {
            autocomplete: Boolean,
            schema: Array
        }
    }
</script>

问题是,表单字段无法正确呈现。查看图片:enter image description here

我想要的是: enter image description here

P.S。:我刚开始学习组件,所以,这可能是一个愚蠢的错误。

1 个答案:

答案 0 :(得分:2)

您要在循环中设置文字值,需要使用v-bind:或速记:

<input
  :type="field.type"
  :name="field.name"
  :id="field.id"
  :class="field.inputClass"
  :placeholder="field.placeholder"
  :required="field.required"
  v-model="field.model"
/>

修改

您无法以这种方式绑定v-model,而是需要将其绑定到数据。最简单的方法是创建一个values数组,然后在你创建的组件钩子中设置它。 Vue不直接绑定到数组,因此您必须将对象推送到数组:

created() {
  this.inputs.forEach((input) => {
    // push new value object to array
    this.values.push({value: input.value})    
  });
},
data() {
  return {
    values: []
  }
}

现在,在v-for内,您可以使用索引将输入绑定到值:

  <div v-for="(input, index) in inputs">
    <input  v-model="values[index].value" />
  </div>

这是工作中的JSFiddle:

https://jsfiddle.net/xsg91o04/