vue使用填坑之:model和v-model的區別

v-model一般用於input的雙向數據綁定 <input v-model="parentMsg">,也能夠實現子組件到父組件數據的雙向數據綁定:
首先說說v-model的用法:this

父組件: spa

   

 <div>
      <input type="text" v-model='msg'>
      <child v-model='msg'></child>
  </div>

子組件: 雙向綁定

 

 Vue.component('child', {
      props: ['value'],
      template: '<input type="text" @input="handleInput" :value=value />',
      methods: {
        handleInput(e){
          console.log(e);
          this.$emit('input', e.target.value);
        }
      }
    })
   new Vue({
    el:'#example',
    data:{
      msg:'好天氣',
      parentMsg:''
    }
   })  

 

 

不管改變父組件仍是子組件的輸入框,value和msg的值都會改變,兩個輸入框的值也就同時改變了。code

 

 :model和v-model的區別
     :model是v-bind:model的縮寫,<child :model="msg"></child>這種只是將父組件的數據傳遞到了子組件,並無實現子組件和父組件數據的雙向綁定。固然引用類型除外,子組件改變引用類型的數據的話,父組件也會改變的。component

相關文章
相關標籤/搜索