默认情况下,组件上的v-model使用modelValue作为prop和update:modelValue作为子组件更新父组件值的事件。我们可以通过向v-model传递参数来修改这些名称:
父组件:
01 | < template > |
02 | <!--这里的v-model必须要,否则的话,只能将keyword传给子组件,却无法实现双向绑定--> |
03 | < zdyinput v-model:keyword = "word" /> |
04 | < br >< br > |
05 | {{word}} |
06 | </ template > |
07 | < script > |
08 | import zdyinput from './zdyinput'; |
09 | export default { |
10 | components:{ |
11 | zdyinput |
12 | }, |
13 | data(){ |
14 | return { |
15 | word: '222' |
16 | } |
17 | }, |
18 | } |
19 | </ script > |
01 | < template > |
02 | <!--update为固定写法,input事件可以换成其他事件--> |
03 | <!--$event.target.value为要更新给父组件keyword的值,不能写keyword,因为这里使用value绑定,不是双向绑定--> |
04 | < input type = "text" :value = "keyword" placeholder = "请输入内容" @ input = "$emit('update:keyword', $event.target.value)" /> |
05 | </ template > |
06 | < script > |
07 | export default { |
08 | props:['keyword'] |
09 | } |
10 | </ script > |
绑定多个v-model和一个差不多,直接看案例:
父组件调用:
01 | <template> |
02 | <user-name v-model:firstName= "name1" v-model:lastName= "name2" /> |
03 | <br><br> |
04 | {{name1}} - {{name2}} |
05 | </template> |
06 | <script> |
07 | import UserName from './UserName' ; |
08 | export default { |
09 | components:{ |
10 | UserName |
11 | }, |
12 | data(){ |
13 | return { |
14 | name1: '' , |
15 | name2: '' |
16 | } |
17 | }, |
18 | methods:{ |
19 | } |
20 | } |
21 | </script> |
01 | <template> |
02 | <input type= "text" :value= "firstName" placeholder= "姓" @input= "$emit('update:firstName', $event.target.value)" /> - |
03 | <input type= "text" :value= "lastName" placeholder= "名" @input= "$emit('update:lastName', $event.target.value)" /> |
04 | </template> |
05 | <script> |
06 | export default { |
07 | props:[ 'firstName' , 'lastName' ] |
08 | } |
09 | </script> |
10 | <style> |
11 | input{ |
12 | width: 100px; |
13 | height: 32px; |
14 | line-height: 32px; |
15 | } |
16 | </style> |
部分素材资源来源网站,本站提供免费下载,如有侵权请联系站长马上删除!