vue 父子组件的方法调用

2023-04-27,,

$emit 子组件触发父组件的方法:

<!-- 子组件 -->
<template>
<div id="child">
<button @click="tryToParent">click</button>
</div>
</template>
<script>
export default {
name: 'child',
methods:{
tryToParent(){
// 通过$emit进行触发
// 第一个参数为父组件监听的事件名,后续参数为父组件方法的参数
this.$emit("toParent","我从子组件传来")
}
}
}
</script> <!-- 父组件 -->
<template>
<div id="parent">
<!-- 监听child的toParent事件广播,用fromChild进行处理 -->
<child @toParent="fromChild"></child>
</div>
</template>
<script>
import child from "./child.vue"
export default {
name: 'parent',
components:{child},
methods:{
fromChild(msg){
console.log(msg); // 点击子组件的button,这里最终打印出“我从子组件传来”
}
}
}
</script>

  $refs 父组件获取子组件实例,进而调用子组件方法或者直接修改子组件属性:

<!-- 子组件 -->
<template>
<div id="child">
<div>{{message1}}</div>
<div>{{message2}}</div>
</div>
</template>
<script>
export default {
name: 'child',
data(){
return {
message1:"",
message2:""
}
},
methods:{
fromParent(msg){
this.message1 = msg
}
}
}
</script> <!-- 父组件 -->
<template>
<div id="parent">
<button @click="toChild">click</button>
<child ref="child"></child>
</div>
</template>
<script>
import child from "./child.vue"
export default {
name: 'parent',
components:{child},
methods:{
toChild(){
/** this.$refs.child返回child组件实例 **/ // 调用子组件的fromParent方法
this.$refs.child.fromParent("我从父组件传递过来")
// 直接修改child的data
this.$refs.child.message2 = "啦啦啦"
}
}
}
</script>

  

vue 父子组件的方法调用的相关教程结束。

《vue 父子组件的方法调用.doc》

下载本文的Word格式文档,以方便收藏与打印。