接上篇,
vue的父組件向子組件獲取值,如果父組件需要主動調用子組件中的屬性方法該如何實現?
獲取方法
1、 父組件中使用子組件的時候在給子組件定義一個ref屬性
2、父組件可以通過this.$refs.XXX,來操作子組件中的屬性和方法
子組件Sub1.vue
<template>
<module :title="title" />
<button :click="run()"></button>
</template>
<script>
export default {
name: "Sub1",
data() {
return {
//父組件可以通過定義的ref調用到title
title: ''
}
}
,methods {
run() {
//父組件可以通過定義的ref調用到該方法。
console.log("sub1");
}
}
}
</script>
父組件
<template>
<!--這里使用子組件的時候定義一個ref屬性1-->
<sub1 ref="sub"/>
<button @click="callChild()"></button>
</template>
<script>//導入子組件import Sub1 from './Sub1.vue'
export default {
name: 'app',
data() {
return {
title : 'test'
}
},methods {
callChild() {
//這里就可以使用到子組件里面的title屬性
console.log(this.$refs.title)
//這樣可以使用到子組件的方法
this.$ref.run();
}
}, components: {
Sub1 //掛載子組件Sub1
}
}
</script>
博主:測試生財(一個不為996而996的測開碼農)
座右銘:專注測試開發與自動化運維,努力讀書思考寫作,為內卷的人生奠定財務自由。
內容范疇:技術提升,職場雜談,事業發展,閱讀寫作,投資理財,健康人生。
csdn:https://blog.csdn.net/ccgshigao
博客園:https://www.cnblogs.com/qa-freeroad/
51cto:https://blog.51cto.com/14900374
微信公眾號:測試生財(定期分享獨家內容和資源)

