1. 程式人生 > 實用技巧 >Vue:v-model的使用

Vue:v-model的使用

1、v-model的基本使用

(1)基本使用

<div id="app">
  <input type="text" v-model="message">
  {{message}}
</div>

<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: 'hello'
    }
  })
</script>

v-model可以實現資料的雙向繫結,普通的方式是頁面從data獲取資料,使用v-model能夠實現雙向繫結,就是在頁面發生變化的時候data也會改變

(2)實現原理

<div id="app">
  <input type="text" :value="message" @input="message = $event.target.value">
  <h2>{{message}}</h2>
</div>

<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: 'hello'
    },
    methods: {
      valueChange(
event) { this.message = event.target.value; } } }) </script>

這是手動實現的雙向繫結

2、與其它標籤的結合使用

(1)與radio的結合使用

<div id="app">
  <label for="male">
    <input type="radio" id="male" value="" v-model="sex"></label>
  <label for="female">
    <input type="
radio" id="female" value="" v-model="sex"></label> <h2>您選擇的性別是: {{sex}}</h2> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { sex: '' } }) </script>

與sex繫結後就可以將選擇的資料提交到伺服器了

(2)與checkbox的結合使用

<div id="app">
  <h2>您的愛好是: {{hobbies}}</h2>
  <label v-for="item in originHobbies" :for="item">
    <input type="checkbox" :value="item" :id="item" v-model="hobbies">{{item}}
  </label>
</div>

<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: '你好啊',
      hobbies: [],
      originHobbies: ['籃球', '足球', '乒乓球', '羽毛球', '檯球', '高爾夫球']
    }
  })
</script>

(3)與select的結合使用

<div id="app">
  <select name="abc" v-model="fruit">
    <option value="蘋果">蘋果</option>
    <option value="香蕉">香蕉</option>
    <option value="榴蓮">榴蓮</option>
    <option value="葡萄">葡萄</option>
  </select>
  <h2>您選擇的水果是: {{fruit}}</h2>
</div>

<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      fruit: '香蕉',
    }
  })
</script>

3、修飾符

(1)lazy

  <input type="text" v-model.lazy="message">

在輸入框綁定了data裡的message之後是隨著輸入框裡的值而實時改變的,在添加了lazy之後只有在敲擊回車之後資料才會同步

(2)number

  <input type="number" v-model.number="age">

頁面輸入的資料是字串型別的,我們需要的可能是數字型別的,這個時候就需要用number修飾符進行資料的型別轉換

(3)trim

  <input type="text" v-model.trim="name">

取出首尾空格,在輸入框中輸入資料的時候可能會在首尾新增很多的空格,但是在添加了trim修飾符後,這些空格都會別去除掉