主要是通過 v-model 對表單元素做數據的 雙向綁定. 用法其實也很簡單, 只是因為表單元素有不同類型, 處理方式有些許不同, 這點需要注意.
1. 如果是 輸入框 , 可以直接使用 v-model="" , 注意這里的 .trim | .number | .lazy 是三個 v-model 的 修飾符. 表示 去除輸入內容的收尾空格 | 將輸入的字符串轉換為數值類型 | 讓數據的更新在輸入改變時進行.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script> <title>Vue Test</title> <style> .style1 { width: 100px; height: 100px; background-color: tomato; text-align: center; line-height: 100px; color: white; cursor: pointer; } </style> </head> <body> <div id="app"> <form action=""> <input type="text" v-model.number.trim.lazy="text" /> <p>{{ text }}</p> </form> </div> <script> var vApp = new Vue({ el: "#app", data: { text: "" } }) </script> </body> </html>
2. 表單中的 多選框 和 復選框 中的 v-model 綁定的是 name 屬性, 只是數據類型不一樣, 多選框 需要用 數組 來裝
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script> <title>Vue Test</title> <style> .style1 { width: 100px; height: 100px; background-color: tomato; text-align: center; line-height: 100px; color: white; cursor: pointer; } </style> </head> <body> <div id="app"> <form action=""> <input id="radio1" type="radio" v-model="radioName" value="radioTest1" /> <label for="radio1">單選示例1</label> <input id="radio2" type="radio" v-model="radioName" value="radioTest2" /> <label for="radio2">單選示例2</label> <p>單選選中狀態: {{ radioName }}</p> <input id="checkbox1" type="checkbox" v-model="checkboxName" value="checkboxTest1" /> <label for="checkbox1">多選示例1</label> <input id="checkbox2" type="checkbox" v-model="checkboxName" value="checkboxTest2" /> <label for="checkbox2">多選示例2</label> <input id="checkbox3" type="checkbox" v-model="checkboxName" value="checkboxTest3" /> <label for="checkbox3">多選示例3</label> <p>多選選中狀態: {{ checkboxName }}</p> </form> </div> <script> var vApp = new Vue({ el: "#app", data: { radioName: false, checkboxName: [] } }) </script> </body> </html>
3. 下面是 下拉列表 的 雙向數據綁定
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script> <title>Vue Test</title> <style> .style1 { width: 100px; height: 100px; background-color: tomato; text-align: center; line-height: 100px; color: white; cursor: pointer; } </style> </head> <body> <div id="app"> <form action=""> <select v-model="selectTest" name="test"> <option value="">請選擇</option> <option value="water">水水水</option> <option value="fire">火火火</option> </select> <p>選擇: {{ selectTest }}</p> </form> </div> <script> var vApp = new Vue({ el: "#app", data: { selectTest: "" } }) </script> </body> </html>