Vue子组件怎么调用父组件的方法 Vue子组件调用父组件函数的三种方法
Vue子组件怎么调用父组件的方法Vue子组件调用父组件函数的三种方法
·
this.$parent.event
父组件中定义一个方法parentFun
<template>
<div>
父组件
<child></child>
</div>
</template>
<script>
import child from './child.vue'
export default {
name: "parent",
components: {
child,
},
data() {
return {
parentFun(cdata){
console.log(cdata,"cdata");
}
};
},
created() {},
mounted() {},
methods: {
},
};
</script>
<style lang='less' scoped>
</style>
子组件中通过this.$parent.parentFun
,来调用父组件的方法。
<template>
<div>
<button @click="childFun">子组件按钮</button>
</div>
</template>
<script>
export default {
name: "child",
components: {
},
data() {
return {
};
},
created() {},
mounted() {},
methods: {
childFun(){
this.$parent.parentFun("子组件数据")
}
},
};
</script>
<style lang='less' scoped>
</style>
this.$emit(“父组件自定义事件”,“子组件要传达到父组件数据”)
在父组件中给子组件上添加一个自定义函数,把父组件中的方法传递进去
<template>
<div>
父组件
<child @fatherMethod="parentFun"></child>
</div>
</template>
<script>
import child from './child.vue'
export default {
name: "parent",
components: {
child,
},
data() {
return {
parentFun(cdata){
console.log(cdata,"cdata");
}
};
},
created() {},
mounted() {},
methods: {
},
};
</script>
<style lang='less' scoped>
</style>
子组件中通过this.$emit("父组件传递过来的函数","子组件数据")
来触发父组件函数
<template>
<div>
<button @click="childFun">子组件按钮</button>
</div>
</template>
<script>
export default {
name: "child",
components: {
},
data() {
return {
};
},
created() {},
mounted() {},
methods: {
childFun(){
this.$emit("fatherMethod","子组件数据")
}
},
};
</script>
<style lang='less' scoped>
</style>
父组件把方法传入子组件中,在子组件里直接调用
父组件
<template>
<div>
父组件
<child :parentFun="parentFun"></child>
</div>
</template>
<script>
import child from './child.vue'
export default {
name: "parent",
components: {
child,
},
data() {
return {
};
},
created() {},
mounted() {},
methods: {
parentFun(cdata){
console.log(cdata);
}
},
};
</script>
<style lang='less' scoped>
</style>
子组件中直接调用方法
<template>
<div>
<button @click="childFun">子组件按钮</button>
</div>
</template>
<script>
export default {
name: "child",
components: {
},
data() {
return {
};
},
created() {},
mounted() {},
methods: {
childFun(){
if (this.parentFun) {
this.parentFun("子组件数据");
}
}
},
};
</script>
<style lang='less' scoped>
</style>
更多推荐
已为社区贡献2条内容
所有评论(0)