Vue $parent、子组件调用父组件方法,父组件调用子组件方法、值
https://blog.csdn.net/zgrkaka/article/details/100528714
·
Vue子组件调用父组件的方法_John的WEB前端学习日记的博客-CSDN博客_子组件调用父组件的方法
父组件调用子组件的值和方法
<HelloWorld ref="Child" :message="message"></HelloWorld>
调用值、方法
this.$refs.Child.属性
this.$refs.Child.方法()
this.$refs.Child.username
this.$refs.Child.getData()
子组件调用父组件的值和方法
this.$parent.属性
this.$parent.方法()
爷组件调用孙组件里面的属性和方法
this.$refs["netheader"].$refs["DatePicker"].属性
this.$refs["netheader"].$refs["DatePicker"].方法()
假设层级太深: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();
this.$nextTick(() => {//一般推荐加nextTick和保证组件有渲染不能v-if
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>
父组件调用子组件
通过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>
更多推荐
已为社区贡献60条内容
所有评论(0)