1. 程式人生 > >vue指令v-model(雙向資料繫結)自動收集資料

vue指令v-model(雙向資料繫結)自動收集資料

前言:表單提交資料在網站頁面中是十分常見的,而這個表單資料的獲取在原生寫法甚至於JQ都是比較麻煩的(首先需要獲取DOM,然後獲取值)。

但是,在vue的專案環境下,表單資料的收集又該怎麼辦呢?(這種自己寫input元素的方法在實際專案中是不常用的哈,因為一般我們都會用一個UI庫,方便而快捷!)

首先,看一下最後的效果:

然後,上一下完整的程式碼:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>08_表單輸入繫結</title>
</head>
<body>
<div id="demo">
  <form action="/xxx" @submit.prevent="handleSubmit">
    <span>使用者名稱: </span>
    <input type="text" v-model="username"><br>

    <span>密碼: </span>
    <input type="password" v-model="pwd"><br>

    <span>性別: </span>
    <input type="radio" id="female" value="女" v-model="sex">
    <label for="female">女</label>
    <input type="radio" id="male" value="男" v-model="sex">
    <label for="male">男</label><br>

    <span>愛好: </span>
    <input type="checkbox" id="basket" value="basket" v-model="likes">
    <label for="basket">籃球</label>
    <input type="checkbox" id="foot" value="foot" v-model="likes">
    <label for="foot">足球</label>
    <input type="checkbox" id="pingpang" value="pingpang" v-model="likes">
    <label for="pingpang">乒乓</label><br>

    <span>城市: </span>
    <select v-model="cityId">
      <option value="">未選擇</option>
      <option :value="city.id" v-for="(city, index) in allCitys" :key="city.id">{{city.name}}</option>
    </select><br>
    <span>介紹: </span>
    <textarea rows="10" v-model="info"></textarea><br><br>

    <input type="submit" value="註冊">
  </form>
</div>

<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
  new Vue({
    el: '#demo',
    data: {
      username: '',
      pwd: '',
      sex: '男',
      likes: ['foot'],
      allCitys: [{id: 1, name: 'BJ'}, {id: 2, name: 'SS'}, {id: 3, name: 'SZ'}],
      cityId: '2',
      info: ''
    },
    methods: {
      handleSubmit () {
        console.log(this.username, this.pwd, this.sex, this.likes, this.cityId, this.info)
        alert('提交註冊的ajax請求')
      }
    }
  })
</script>
</body>
</html>

 

v-model自動收集資料使用總結:

1. 在input標籤中使用 v-model 指令後,input的value屬性將自動和v-model的值想繫結(簡單來說:v-model繫結的是input的value屬性)

2. 在繫結type為radio和checkbox  的input標籤的時候,也必須給這兩種型別的input新增value屬性

3. type為radio的input(單選框),必須一組單選框v-model的值的相同的,而最後的值是選擇的單選框對應的value值

4. type為checkbox的input(複選框),必須一組複選框v-model的值的相同的,而最後的值是選擇的複選框對應的value值(陣列)

5. select(下拉框)中使用 v-model 時( v-model 是使用在select標籤上,即父級標籤上),需要在其子標籤 option 中設定value值(一般option都是遍歷一個數組而產生)。而最後的值是被選中的option(子標籤)對應的 value 值。(一般是option對應的id)

6.   .prevent : 阻止事件的預設行為 event.preventDefault()

      .stop : 停止事件冒泡 event.stopPropagation()

 

文章僅為本人學習過程的一個記錄,僅供參考,如有問題,歡迎指出!