Vue $parent、子组件调用父组件方法,父组件调用子组件方法
https://blog.csdn.net/zgrkaka/article/details/100528714
假设层级太深:this.$parent.$parent.getShopCart() 多加一个 $parent 一般两个够了
子组件调用父组件方法
第一种方法是直接在子组件中通过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>
父组件调用子组件
https://www.cnblogs.com/yuzhongyu/p/10825824.html
通过ref直接调用子组件的方法
//父组件中
<template>
<div>
<Button @click="handleClick">点击调用子组件方法</Button>
<Child ref="child"/>
</div>
</template>
<script>
import Child from './child';
export default {
methods: {
handleClick() {
this.$refs.child.sing();
},
},
}
</script>
//子组件中
<template>
<div>我是子组件</div>
</template>
<script>
export default {
methods: {
sing() {
console.log('我是子组件的方法');
},
},
};
</script>
还没有评论,来说两句吧...