javascript - vue如何綁定動(dòng)態(tài)屬性為根級(jí)響應(yīng)?
問題描述
用戶需要填寫多個(gè)被保險(xiǎn)人的信息,但是被保險(xiǎn)人數(shù)n是從上一頁傳過來的。由于 Vue 不允許動(dòng)態(tài)添加根級(jí)響應(yīng)式屬性,所以你必須在初始化實(shí)例前聲明根級(jí)響應(yīng)式屬性。但被保人list長度是動(dòng)態(tài)的,那么該如何綁定所有的被保人信息相關(guān)數(shù)據(jù)。例如n=1時(shí):
insurant: [ {'insurantName': null,'mobileTelephone': null,'certificateNumber': null,'sex': null,'birth': null }]
n=2時(shí):
insurant: [ {'insurantName': null, 'mobileTelephone': null, 'certificateNumber': null, 'sex': null, 'birth': null }, {'insurantName': null, 'mobileTelephone': null, 'certificateNumber': null, 'sex': null, 'birth': null }]
初始化時(shí)
<template> <p v-for='n in insurant.length'><input v-model='insurant[n].insurantName'> </p></template>data(){ return {insurant: [] }}
當(dāng)被保人數(shù)n是動(dòng)態(tài)時(shí),v-model='insurant[n].insurantName'會(huì)報(bào)錯(cuò)。這種情況該如何在template里綁定被保人insurant所有數(shù)據(jù)呢?求指教多謝
問題解答
回答1:你可以試試: https://jsfiddle.net/milu2003...我的例子可以通過。
你的循環(huán)有問題把。
<p v-for='n in insurant.length'><input v-model='insurant[n].insurantName'> </p>
你這個(gè)循環(huán)寫法很奇怪。我特意去vue官網(wǎng)看了例子,發(fā)現(xiàn)不是這樣寫的。官網(wǎng)的例子是這樣的:
<li v-for='item in items'> {{ item.message }} </li>
https://cn.vuejs.org/v2/guide...
你這里的n輸出1、2.那么insurant[n]出錯(cuò)是必然的。
回答2:<!DOCTYPE html><html><head> <meta charset='UTF-8'></head><body> <p id='app'><input type='number' v-model='count' /><p v-for='i in count'> <com1></com1></p><button @click='submit'>submit</button> </p> <script src='http://cdn.bootcss.com/vue/2.1.0/vue.min.js'></script> <script>Vue.component(’com1’, { template: ’<input type='text' v-model='name' />’, data() {return { name: null} }})new Vue({ el: ’#app’, data() {return { count: 3} }, methods: {submit() { console.log(this.$children.map(t => t.name))} }}) </script></body></html>
相關(guān)文章:
1. android - weex 項(xiàng)目createInstanceReferenceError: Vue is not defined2. android - 哪位大神知道java后臺(tái)的api接口的對(duì)象傳到前端后輸入日期報(bào)錯(cuò),是什么情況?求大神指點(diǎn)3. pdo 寫入到數(shù)據(jù)庫的內(nèi)容為中文的時(shí)候?qū)懭雭y碼4. PHPExcel表格導(dǎo)入數(shù)據(jù)庫怎么導(dǎo)入5. javascript - 如圖,百度首頁,查看源代碼為什么什么都沒有?6. vue2.0+webpack 如何使用bootstrap?7. PHP類封裝的插入數(shù)據(jù),總是插入不成功,返回false;8. mac連接阿里云docker集群,已經(jīng)卡了2天了,求問?9. python - 小白django提交數(shù)據(jù)后,沒有存儲(chǔ)到數(shù)據(jù)庫(查閱資料并沒有發(fā)現(xiàn)問題)10. javascript - 前端開發(fā)框架express,在他的模板引擎下怎么給按鈕添加綁定事件?
