Vue組件間傳值 v-model

使用過Vue的同窗應該都瞭解組件之間傳值javascript

父組件 --> 子組件 : propshtml

子組件 --> 父組件 : 事件java

其實有一種更爲簡單的方法,是基於上述兩種方法,那就是 v-modelapp

咱們都在表單中使用過 v-model 來綁定數據,其實組件之間也是能夠用 v-model 進行雙向綁定的this

咱們來了解一下 v-model 的緣由spa

<input type="text" v-model="message" />
<!--其實上面這種寫法只是一個語法糖,本質以下-->
<input type="text" v-bind:value="message" v-on:input="message = $event.target.value" />

由此看出 v-model 的本質就是綁定一個屬性和事件雙向綁定

所以在組件中能夠這樣使用code

<!--html-->
<my-component v-model="message"></my-component>

<!--JS-->
Vue.component('my-component',{
    template: `<select @change="changeSelect()" ref="selector">
                    <option value="0">javascript</option>
                    <option value="1">PHP</option>
                    <option value="2">C#</option>
                </select>`,
    props:['value'],
    methods: {
        changeSelect(){
            this.$emit('input',this.$refs.selector.value)
        }
    }
})

var app = new Vue({
    el : '#app',
    data(){
        return {
            message : 1
        }
    }
})
相關文章
相關標籤/搜索