在此总结下,供参考!
一、先上结果图,如下:
二、项目说明
红色圈起来的为子组件,绿色圈起来的为父组件。
uni-app项目,所以具体组件引入流程不在详细说明,直接列出代码。
三、代码
1、子组件child.vue
<template>
<view class="" @click="getFatherMethod">
点击调用父组件中的方法
</view>
</template>
<script>
export default{
methods:{
// 定义子组件中的方法
childMethod(){
console.log("我是子组件中的方法childMethod。。。。。。")
},
// 调用父组件中的方法fatherMethod
getFatherMethod(){
this.$emit("getValue");
}
}
}
</script>
<style>
</style>
2、父组件index.vue
<template>
<view class="father-wrap">
<text>父组件页面show</text>
<child @getValue="fatherMethod" ref="sonMethod" :res="list" :kk="df"></child>
<text @click="getChildMethod">点击调用子组件中的方法</text>
</view>
</template>
<script>
// 引入子组件
import child from '../../components/child.vue'
export default {
components:{
child
},
methods:{
// 定义父组件中的方法
fatherMethod(){
console.log("我是父组件里的方法fatherMethod。。。。。。")
},
// 调用子组件中的方法childMethod
getChildMethod(){
this.$refs.sonMethod.childMethod();
}
}
}
</script>
<style>
.father-wrap{
font-size:30upx;
line-height: 80upx;
letter-spacing: 4upx;
}
</style>
说明:子组件调用父组件中的方法,用$emit方法。
父组件调用子组件中的方法用:子组件上定义ref="refName", 父组件的方法中用 this.$refs.refName.去调用子组件方法
此处即为 ref="sonMethod this.$refs.sonMethod.childMethod();