接上篇,vue的父组件向子组件获取值,如果父组件需要主动调用子组件中的属性方法该如何实现?

获取方法
1、 父组件中使用子组件的时候在给子组件定义一个ref属性
2、父组件可以通过this.$refs.XXX,来操作子组件中的属性和方法
子组件Sub1.vue
<template>
<module :title="title" />
<button :click="run()"></button>
</template>
<script> export {
name: "Sub1",
data() { {
//父组件可以通过定义的ref调用到title
title: ''
}
}
,methods {
run() {
console.log("sub1"); }
}
}</script>
父组件
<template>
<!--这里使用子组件的时候定义一个ref属性1-->
<sub1 ="sub"/>
<button @click="callChild()"></button>
</template>
<script>export {
name: 'app',
data() { {
title : 'test'
}
},methods {
callChild() {
//这里就可以使用到子组件里面的title属性
console.log(this.$refs.title)
//这样可以使用到子组件的方法
this.$ref.run();
}
}, components: {
Sub1 }
}</script>
博主:测试生财
座右铭:专注测试与自动化,致力提高研发效能;通过测试精进完成原始积累,通过读书理财奔向财务自由。
csdn:https://blog.csdn.net/ccgshigao
博客园:https://www.cnblogs.com/qa-freeroad/
51cto:https://blog.51cto.com/14900374
Ctrl+Enter 发布
发布
取消