Vue2 props $emit ref 的使用方式

props ,$emit , ref 传值的使用方式

    1. props 和 $emit 的使用
	<template>
    <div class="other">
        <h1>这是 子组件 页面 </h1>
        <h3>{{ msg }}</h3>
        <button @click="sendPar">传父组件值</button>
          <button @click="sendPar">传父组件值</button>
        <br> <br><br>
        <span> {{ num }}</span>
    </div>
</template>
<script>
export default {
    name: 'Other',
    components: {},
    props: ["msg"],
    data() {
        return {
            num: 0
        }
    },
    methods: {
        sendPar() {
            this.$emit("sendPar", "我是other子组件过来的")
        },
        // 子组件定义事件 添加
        add() {
            this.num++
        },
        // 子组件定义事件 减少
        subtract() { this.num--}
    }
};
</script>
    1. refs 和 $emit(sendPar)的使用
<template>
    <div class="about">
        <h1>这是 父组件 页面</h1>
        <other_page :msg='msg' @sendPar="sendPar" ref="other"></other_page>
        <button @click="add"></button> &nbsp;&nbsp;&nbsp;&nbsp; <button @click="subtract"></button>
    </div>
</template>

<script>
import other_page from '../Other/index'
export default {
    name: "About",
    components: {other_page},
    data() {
        return {
            msg: "我是父组件 about 里的数据"
        }
    },
    methods: {
        sendPar(val) {
            this.msg = val
        },
        // 在父组件中 使用 ref 调用 子组件 添加事件
        add() {
            this.$refs.other.add()
        },
        subtract() {
            this.$refs.other.subtract()
        }
    }
}
</script>
    1. $emit 的 sync 的使用方式
<!-- 子组件 -->
<template>
    <div>
        <el-button @click="updateData">子组件</el-button>
    </div>
</template>
<script>
export default {
    methods: {
        updateData() {
            const data = new Date().getFullYear();
            this.$emit('update:dataVal', data);
        }
    }
}
</script>

<!-- 父组件 -->
<template>
    <div>
        <updateDemo :dataVal.sync="message" />
        <p>{{ message }}</p>
        <el-input v-model="message"></el-input>
    </div>
</template>

<script>
import updateDemo from '../common/update.demo.vue';
export default {
    components: {
        updateDemo
    },
    data() {
        return {
            message: '测试数据'
        };
    },
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值