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>
网友评论