v-model
指令在表單元素上建立雙向數據綁定,它負責用於監聽用戶輸入事件以更新數據html
注意,v-model
會忽略全部表單元素特性的初始值,而老是將 Vue 實例的數據做爲數據來源vue
<!DOCTYPE html> <html> <head> <title>Demo</title> <script src="https://cdn.jsdelivr.net/npm/vue"></script> </head> <body> <div id="app"> <input v-model="message" placeholder="請輸入內容"> <span>輸入的值爲: {{ message }}</span> </div> <script> new Vue({ el: '#app', data: { message: '' // string 類型 } }) </script> </body> </html>
<!DOCTYPE html> <html> <head> <title>Demo</title> <script src="https://cdn.jsdelivr.net/npm/vue"></script> </head> <body> <div id="app"> <input type="radio" id="apple" value="Apple" v-model="picked"> <label for="apple">Apple</label> <br> <input type="radio" id="orange" value="Orange" v-model="picked"> <label for="orange">Orange</label> <br> <span>選中的值爲: {{ picked }}</span> </div> <script> new Vue({ el: '#app', data: { picked: '' // string 類型 } }) </script> </body> </html>
<!DOCTYPE html> <html> <head> <title>Demo</title> <script src="https://cdn.jsdelivr.net/npm/vue"></script> </head> <body> <div id="app"> <input type="checkbox" id="bool" v-model="checked"> <label for="bool">{{ checked }}</label> </div> <script> new Vue({ el: '#app', data: { checked: false // boolean 類型 } }) </script> </body> </html>
<!DOCTYPE html> <html> <head> <title>Demo</title> <script src="https://cdn.jsdelivr.net/npm/vue"></script> </head> <body> <div id="app"> <input type="checkbox" id="apple" value="Apple" v-model="checked"> <label for="apple">Apple</label> <input type="checkbox" id="orange" value="Orange" v-model="checked"> <label for="orange">Orange</label> <br> <span>選擇的值爲: {{ checked }}</span> </div> <script> new Vue({ el: '#app', data: { checked: [] // array 類型 } }) </script> </body> </html>
<!DOCTYPE html> <html> <head> <title>Demo</title> <script src="https://cdn.jsdelivr.net/npm/vue"></script> </head> <body> <div id="app"> <select v-model="selected"> <option disabled value="">請選擇</option> <option>Apple</option> <option>Orange</option> </select> <span>選擇的值爲: {{ selected }}</span> </div> <script> new Vue({ el: '#app', data: { selected: '' // string 類型 } }) </script> </body> </html>
<!DOCTYPE html> <html> <head> <title>Demo</title> <script src="https://cdn.jsdelivr.net/npm/vue"></script> </head> <body> <div id="app"> <select multiple v-model="selected"> <option>Apple</option> <option>Banana</option> <option>Cherry</option> <option>Durian</option> <option>Orange</option> </select> <span>選擇的值爲: {{ selected }}</span> </div> <script> new Vue({ el: '#app', data: { selected: [] // array 類型 } }) </script> </body> </html>
.lazy
:在默認狀況下,input 事件觸發後同步數據,使用 .lazy
可指定 change 事件觸發後同步數據npm
<input v-model.lazy="msg" >
.number
:將用戶輸入的值自動轉換爲數值類型app
<input v-model.number="age" type="number">
.trim
:將用戶輸入的值過濾掉首位空白字符學習
<input v-model.trim="msg">
【 閱讀更多 Vue 系列文章,請看 Vue學習筆記 】spa