Vue官网
仅仅是个人学习的记录
- 通过ref直接调用子组件的方法
这里子组件中定义一个方法sayHi:
<template>
<div>我是子组件</div>
</template>
<script>
export default {
name: "ChildModule",
methods: {
sayHi() {
this.$toast({message: 'Hi'})
},
}
}
</script>
<style scoped lang="less">
</style>
父组件:
<template>
<div class="layout">
<child-module ref="child"></child-module>
<van-button
type="primary"
@click="callChildSayHi">
调用子组件中的sayHi方法
</van-button>
</div>
</template>
<script>
import ChildModule from "../../components/child-module";
export default {
name: "CurtisTest",
components: {
ChildModule
},
data() {
return {
}
},
methods: {
callChildSayHi() {
this.$refs.child.sayHi();
},
}
}
</script>
<style scoped lang="less">
.layout {
display: flex;
flex-direction: column;
align-items: center;
margin: 16px;
padding: 16px;
}
</style>
总结:
1> 子组件中定义方法
2> 父组件引用并使用子组件,给子组件设置属性ref值
3> this.$refs.ref名.子组件的方法名
- 通过组件的on方法
子组件:
<template>
<div>我是子组件</div>
</template>
<script>
export default {
name: "ChildModule",
mounted() {
this.$nextTick(function () {
this.$on('sayHi', function () {
this.$toast({message: 'Hi'})
})
})
}
}
</script>
<style scoped lang="less">
</style>
父组件:
<template>
<div class="layout">
<child-module ref="child"></child-module>
<van-button
type="primary"
@click="callChildSayHi">
调用子组件中的sayHi方法
</van-button>
</div>
</template>
<script>
import ChildModule from "../../components/child-module";
export default {
name: "CurtisTest",
components: {
ChildModule
},
data() {
return {
}
},
methods: {
callChildSayHi() {
this.$refs.child.$emit("sayHi"); // 子组件$on中的名字
},
}
}
</script>
<style scoped lang="less">
.layout {
display: flex;
flex-direction: column;
align-items: center;
margin: 16px;
padding: 16px;
}
</style>
===>> 使用第一种方法即可