2021-05-09

Vue中子组件向父组件传递数据的方式

Vue组件之间的关系可分为父子组件通信,兄弟组件通信,跨级组件通信。本文将具体介绍子组件向父组件传递数据的方式。

1. 自定义事件

通过自定义事件改变父组件数据

例如:

父组件:

//全局注册父组件
Vue.component("parentcom", {
    data() {
        return {
            name: ''
        }
    },
    template: `
        <div>
            <p>这是父组件</p>
            // 自定义test事件,父组件触发 test事件,会触发 testHandle事件
            <childcom @test="testHandle"></childcom>
            //触发父组件事件时,还会将 name数据传递给父组件    
            <p>从子组件接收到的数据为:{{name}}</p>
        </div>
    `,
    methods: {
        testHandle(str) {
            this.name = str;
        }
    }
});

子组件:

//全局注册子组件
Vue.component("childcom", {
    data() {
        return {
            name: "zhangsan",
        }
    },
    template: `
        <div>
            <p>这是子组件</p>  
            <button @click=clickHandle>click</button> 
        </div>
    `,
    methods: {
            
        clickHandle() {
            this.$emit("test", this.name)
        }
    }
});

2.使用v-model

通过在自定义组件上使用v-model指令

例如:

父组件:

//全局注册父组件
Vue.component("parentcom", {
    data() {
        return {
            counter: 1
        }
    },
    template: `
        <div>
            <p>这是父组件</p>
            <p>{{counter}}</p>
            <childcom v-model="counter"></childcom>
        </div>
    `
});

 子组件:

//全局注册子组件
Vue.component("childcom", {
    data() {
        return {
            counter2: 1
        }
    },
    template: `
        <div> 
            <button @click=clickHandle>+1</button> 
        </div>
    `,
    methods: {
        clickHandle() {
            this.counter2++;
            this.$emit("input", this.counter2);
        }
    }
});

3.通过.sync修饰符

在vue@1.x使用.sync修饰符可以实现数据的双向绑定,即子组件可以修改父组件中的值。但在vue@2.0是阶段被删除了。在vue@2.3.0+ 以上版本又重新引入,它会被扩展为一个自动更新父组件属性的 v-on 监听器。就是让我们手动进行更新父组件中的值,从而使数据改动来源更加的明显。

例如:

父组件:

//全局注册父组件
Vue.component("parentcom", {
    data() {
        return {
            counter: 1
        }
    },
    template: `
        <div>
            <p>这是父组件</p>
            <p>{{counter}}</p>
            // 通过.sync修饰符绑定
            <childcom :foo.sync="counter"></childcom>
        </div>
    `
});

 子组件:


//全局注册子组件
Vue.component("childcom", {
    data() {
        return {
            counter2: 1
        }
    },
    template: `
        <div> 
            <button @click=clickHandle>+1</button> 
        </div>
    `,
    methods: {
        clickHandle() {
            this.counter2++;
            this.$emit("update:foo", this.counter2);
        }
    }
});

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值