學習了一段時間的vue,並嘗試着作了幾個小項目,在項目中發現了一個問題,就是在寫組件的時候,遇到input框時,外部怎麼實時取到組件內部input的值的問題。上網查了一下i,本身有也嘗試了。javascript
首先先了解了v-model的真正的狀況:css
<input type="text" v-model="val">
等同於html
<input type="text" :value="val" @input="val=$event.target.value">
能夠看到,實際上就是綁定了一個value屬性,而後去監聽input時間,實時的更新當前的value值。vue
那麼咱們能夠借用這個思想,再加上計算屬性的get和set去控制組件內部的值和組件外部的v-model的值的綁定:java
<!DOCTYPE html> <html> <head> <title></title> <script src="https://cdn.bootcss.com/vue/2.5.13/vue.js"></script> </head> <body> <div id="app"> <!-->等同於<my-component :value="parentValue" @input="parentValue=$event.target.value"></my-component><--> <my-component v-model="parentValue"></my-component> <p>{{parentValue}}</p> </div> <script type="text/javascript"> Vue.component('my-component',{ template:`<input type="text" v-model="currentValue">`, props:['value'],//收到value computed: { currentValue: { get () {//動態設置子組件的input值 return this.vlaue }, set (val) {//當子組件input的值發生變更的時候,通知父組件也更新 this.$emit('input', val) } } } }) new Vue({ el: '#app', data:{ parentValue: '' } }) </script> </body> </html>