javascript - vue如何綁定動(dòng)態(tài)屬性為根級(jí)響應(yīng)?
問(wèn)題描述
用戶需要填寫(xiě)多個(gè)被保險(xiǎn)人的信息,但是被保險(xiǎn)人數(shù)n是從上一頁(yè)傳過(guò)來(lái)的。由于 Vue 不允許動(dòng)態(tài)添加根級(jí)響應(yīng)式屬性,所以你必須在初始化實(shí)例前聲明根級(jí)響應(yīng)式屬性。但被保人list長(zhǎng)度是動(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ù)呢?求指教多謝
問(wèn)題解答
回答1:你可以試試: https://jsfiddle.net/milu2003...我的例子可以通過(guò)。
你的循環(huán)有問(wèn)題把。
<p v-for='n in insurant.length'><input v-model='insurant[n].insurantName'> </p>
你這個(gè)循環(huán)寫(xiě)法很奇怪。我特意去vue官網(wǎng)看了例子,發(fā)現(xiàn)不是這樣寫(xiě)的。官網(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. 在windows下安裝docker Toolbox 啟動(dòng)Docker Quickstart Terminal 失敗!2. python3.x - python連oanda的模擬交易api獲取json問(wèn)題第五問(wèn)3. macos - mac下docker如何設(shè)置代理4. 如何解決Centos下Docker服務(wù)啟動(dòng)無(wú)響應(yīng),且輸入docker命令無(wú)響應(yīng)?5. 在mac下出現(xiàn)了兩個(gè)docker環(huán)境6. android - Python代碼轉(zhuǎn)為java代碼?7. css如何隱藏滾動(dòng)條?8. atom開(kāi)始輸入!然后按tab只有空格出現(xiàn)沒(méi)有html格式出現(xiàn)9. javascript - vue異步數(shù)據(jù)打印問(wèn)題10. python 正則表達(dá)式提取
