第一种方法是直接在子组件中通过this.$parent.event来调用父组件的方法
父组件
<template>
<div>
<child></child>
</div>
</template>
<script>
import child from '~/components/dam/child';
export default {
components: {
child
},
methods: {
fatherMethod() {
console.log('测试');
}
}
};
</script>
子组件
<template>
<div>
<button @click="childMethod()">点击</button>
</div>
</template>
<script>
export default {
methods: {
childMethod() {
this.$parent.fatherMethod();
}
}
};
</script>
第二种方法是在子组件里用$emit向父组件触发一个事件,父组件监听这个事件就行了。
父组件
<template>
<div>
<child @fatherMethod="fatherMethod"></child>
</div>
</template>
<script>
import child from '~/components/dam/child';
export default {
components: {
child
},
methods: {
fatherMethod() {
console.log('测试');
}
}
};
</script>
子组件
<template>
<div>
<button @click="childMethod()">点击</button>
</div>
</template>
<script>
export default {
methods: {
childMethod() {
this.$emit('fatherMethod');
}
}
};
</script>
第三种是父组件把方法传入子组件中,在子组件里直接调用这个方法
父组件
<template>
<div>
<child :fatherMethod="fatherMethod"></child>
</div>
</template>
<script>
import child from '~/components/dam/child';
export default {
components: {
child
},
methods: {
fatherMethod() {
console.log('测试');
}
}
};
</script>
子组件
<template>
<div>
<button @click="childMethod()">点击</button>
或者
<button @click="childMethod">点击</button><!--childMethod直接调用props的传过来的fatherMethod方法-->
</div>
</template>
<script>
export default {
props: {
fatherMethod: {
type: Function,
default: null
}
},
methods: {
childMethod() {
if (this.fatherMethod) {
this.fatherMethod();
}
}
}
};
</script>
+父组件调用子组件方法
父组件
<template>
<child-item ref='child' />
<button @click='useChildFun'></button>
</template>
<script>
methods() {
useChildFun:function(){
this.$refs.child.usedInPar('调用子组件中的方法');
}
}
</script>
子组件
methods () {
usedInPar(str){
console.log(str);
}
}
第二种
<template>
<div>
<h2>我是父组件:</h2>
<div>
<input v-model="parementMsg">
</div>
<div>
<!-- 3.向子组件 传参 -->
<Child2 :fromParentMsg="parementMsg"></Child2>
<button @click="parent_child_fun">调用子组件的方法</button>
</div>
</div>
</template>
<script>
// 1.引入子组件
import Child2 from "@/components/Child2"
export default {
data() {
return {
parementMsg: ''
}
},
mounted() {
// $children 是一个数组 获取子组件的属性
console.log(this.$children[0].child_msg)
// 获取子组件的方法
console.log(this.$children[0].child_fun())
},
methods: {
parent_child_fun() {
this.$children[0].child_fun()
}
},
// 2.在父组件中注册
components: {
Child2
}
}
</script>
子组件
<template>
<div>
这是子组件的内容-来自父组件:{{fromParentMsg}}
</div>
</template>
<script>
export default {
// props 接受父组件传递的值
props:['fromParentMsg'],
data() {
return {
child_msg:"这是child的msg"
}
},
methods:{
child_fun(){
alert('23452344')
}
}
}
</script>
<style scoped>
</style>
网友评论