本文将介绍单选框(radio)的双向绑定,例如:
<input type="radio" id="one" value="One1" v-model="picked">
注意,如果数据域 picked 的值为 “One1”,则选中该单选框。否则,不选中任何单选框。
将两个单选框双向绑定到数据域 picked 属性,如下:
<html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vue</title> <!-- 使用 CDN 引入 Vue 库 --> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> </head> <body> <div id="app"> <input type="radio" id="one" value="One1" v-model="picked"> <label for="one">One</label> <br> <input type="radio" id="two" value="Two2" v-model="picked"> <label for="two">Two</label> <br> <span>Picked: {{ picked }}</span> </div> <script type="text/javascript"> var app = new Vue({ el: "#app", data: { // 设置默认选中 One 单选框,如果设置为空字符串,则不选中任何单选框 picked: 'One1' } }); </script> </body> </html>
运行效果: