this.$refs与this.$emit()

this.$refs
父组件向子组件通信,可以调用子组件里的属性和方法

示例

父组件

<template>
<child ref="msg" />
</template>
<script>
import child from "./child.vue";
export default {
name: "parent",
components: {child},
mounted(){
// 通过ref定位组件并调用组件的方法
this.$refs.msg.setMessage("我是子组件")
}
}
</script>

子组件

<template>
<h1>{{msg}}</h1>
</template>
<script>
export default {
name: "",
data(){
return {
msg: ""
}
},
methods: {
setMessage(msg){
this.msg = msg;
}
}
}
</script>

this.$emit()
子组件向父组件通信

使用方式

vm.$emit( event, arg )

示例

父组件

<template>
<!-- 通过绑定子组件定义的getMessage事件获取信息 -->
<child @getMessage="showMessage" />
</template>
<script>
import child from "./child.vue";
export default {
name: "parent",
components: {child},
methods: {
showMessage(msg){
console.log(msg)
}
}
}
</script>

子组件

<template>
<h1>{{msg}}</h1>
</template>
<script>
export default {
name: "",
data(){
return {
msg: "hello"
}
},
methods: {
getMessage(){
this.$emit("getMessage", this.msg)
}
}
}
</script>
posted @   SultanST  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示