Vue组件间的通信

2017-12-15  本文已影响7人  _imp_

父组件向子组件通信

第一步,引用子组件的时候传入数据

new Vue({
    el: "#app",
    data: {
        count: 0,
        fatherlist: ["武汉", "深圳", "广州"]
    }
})
<custom-select :list="fatherlist">
    <div>子组件</div>
</custom-select>

第二步,在子组件中显示声明拥有该属性

props: {
    list: {
        type: Array     // 定义属性的类型,多类型用[], 如[String, Number]
        // default: [],    // 默认值
        // required: true     //必传参数
        // validator(value){    //验证规则
        //     return value.length > 0;
        // }
    }
}

第三步,子组件使用数据

<select>
    <option v-for="item in list">{{ item }}</option>
</select>

子组件向父组件通信

第一步,父组件定义执行方法

methods: {
    countHandle(){
        console.log("子组件点击了");
    }
}

第二步,在子组件中绑定事件

<custom-select :list="fatherlist" @increment-click="countHandle"></custom-select>

第三步,在子组件中触发事件

<input type="button" value="改变count的值" @click="changeCount"/>
methods: {
    changeCount(){
        // 通知父组件执行事件
        this.$emit("increment-click");          
    }
}
上一篇 下一篇

猜你喜欢

热点阅读