本文介紹了Vue 表單控件綁定的實現示例,感覺這個地方知識點挺多的,而且很重要,所以,今天添加一點小筆記。
基礎用法
可以用 v-model 指令在表單控件元素上創建雙向數據綁定。根據控件類型它自動選取正確的方法更新元素。盡管有點神奇,v-model 不過是語法糖,在用戶輸入事件中更新數據,以及特別處理一些極端例子。
Text
<span>Message is: {{ message }}</span><br><input type="text" v-model="message" placeholder="edit me">Checkbox
單個勾選框,邏輯值:
<input type="checkbox" id="checkbox" v-model="checked"><label for="checkbox">{{ checked }}</label>多個勾選框,綁定到同一個數組:
<input type="checkbox" id="jack" value="Jack" v-model="checkedNames"><label for="jack">Jack</label><input type="checkbox" id="john" value="John" v-model="checkedNames"><label for="john">John</label><input type="checkbox" id="mike" value="Mike" v-model="checkedNames"><label for="mike">Mike</label><br><span>Checked names: {{ checkedNames | json }}</span>new Vue({ el: '...', data: { checkedNames: [] }})Radio
<input type="radio" id="one" value="One" v-model="picked"><label for="one">One</label><br><input type="radio" id="two" value="Two" v-model="picked"><label for="two">Two</label><br><span>Picked: {{ picked }}</span>Select
單選:
<select v-model="selected"> <option selected>A</option> <option>B</option> <option>C</option></select><span>Selected: {{ selected }}</span>多選(綁定到一個數組):
<select v-model="selected" multiple> <option selected>A</option> <option>B</option> <option>C</option></select><br><span>Selected: {{ selected | json }}</span>動態選項,用 v-for 渲染:
<select v-model="selected"> <option v-for="option in options" v-bind:value="option.value"> {{ option.text }} </option></select><span>Selected: {{ selected }}</span>new Vue({ el: '...', data: { selected: 'A', options: [ { text: 'One', value: 'A' }, { text: 'Two', value: 'B' }, { text: 'Three', value: 'C' } ] }})值綁定
對于單選按鈕,勾選框及選擇框選項,v-model 綁定的值通常是靜態字符串(對于勾選框是邏輯值):
<!-- 當選中時,`picked` 為字符串 "a" --><input type="radio" v-model="picked" value="a"><!-- `toggle` 為 true 或 false --><input type="checkbox" v-model="toggle"><!-- 當選中時,`selected` 為字符串 "abc" --><select v-model="selected"> <option value="abc">ABC</option></select>
新聞熱點
疑難解答
圖片精選