“Vue从入门到实战:复选框”的版本间的差异
来自CloudWiki
第43行: | 第43行: | ||
</body> | </body> | ||
</html></nowiki> | </html></nowiki> | ||
+ | |||
+ | 改进版:使用v-for指令循环渲染 | ||
+ | |||
+ | <nowiki> | ||
+ | <!DOCTYPE html> | ||
+ | <html> | ||
+ | <head> | ||
+ | <meta charset="UTF-8"> | ||
+ | <title></title> | ||
+ | </head> | ||
+ | <body> | ||
+ | <div id = "app"> | ||
+ | <h3>单个复选框:</h3> | ||
+ | <input id="agreement" type="checkbox" v-model="isAgree"> | ||
+ | <label for="agreement">{{ isAgree }}</label> | ||
+ | |||
+ | <h3>多个复选框:</h3> | ||
+ | <template v-for="option in options" > | ||
+ | <input v-bind:id="option.value" type="checkbox" v-bind:value="option.text" v-model="interests"> | ||
+ | <label v-bind:for="option.value">{{option.text}}</label> | ||
+ | </template> | ||
+ | |||
+ | |||
+ | |||
+ | <p>你的兴趣爱好是: {{ interests }}</p> | ||
+ | </div> | ||
+ | |||
+ | <script src="vue.js"></script> | ||
+ | <script> | ||
+ | var vm = new Vue({ | ||
+ | el: '#app', | ||
+ | data: { | ||
+ | isAgree: false, | ||
+ | interests: [], | ||
+ | options:[ | ||
+ | {text: '足球', value: 'football'}, | ||
+ | {text: '篮球', value: 'basketball'}, | ||
+ | {text: '游泳', value: 'swimming'} | ||
+ | ] | ||
+ | } | ||
+ | }); | ||
+ | </script> | ||
+ | </body> | ||
+ | </html> | ||
+ | </nowiki> |
2021年2月10日 (三) 02:15的最新版本
复选框在单独使用和多个复选框一起使用时,v-model绑定的值会有所不同,
对于前者,绑定的是布尔值,选中则值为true
后者绑定的是同一个数组,选中时复选框的值被保存到数组中。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id = "app"> <h3>单个复选框:</h3> <input id="agreement" type="checkbox" v-model="isAgree"> <label for="agreement">{{ isAgree }}</label> <h3>多个复选框:</h3> <input id="basketball" type="checkbox" value="篮球" v-model="interests"> <label for="basketball">篮球</label> <input id="football" type="checkbox" value="足球" v-model="interests"> <label for="football">足球</label> <input id="volleyball" type="checkbox" value="排球" v-model="interests"> <label for="volleyball">排球</label> <input id="swim" type="checkbox" value="游泳" v-model="interests"> <label for="swim">游泳</label> <p>你的兴趣爱好是: {{ interests }}</p> </div> <script src="vue.js"></script> <script> var vm = new Vue({ el: '#app', data: { isAgree: false, interests: [] } }); </script> </body> </html>
改进版:使用v-for指令循环渲染
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id = "app"> <h3>单个复选框:</h3> <input id="agreement" type="checkbox" v-model="isAgree"> <label for="agreement">{{ isAgree }}</label> <h3>多个复选框:</h3> <template v-for="option in options" > <input v-bind:id="option.value" type="checkbox" v-bind:value="option.text" v-model="interests"> <label v-bind:for="option.value">{{option.text}}</label> </template> <p>你的兴趣爱好是: {{ interests }}</p> </div> <script src="vue.js"></script> <script> var vm = new Vue({ el: '#app', data: { isAgree: false, interests: [], options:[ {text: '足球', value: 'football'}, {text: '篮球', value: 'basketball'}, {text: '游泳', value: 'swimming'} ] } }); </script> </body> </html>