使用ref訪問子組件實體或子元素
點擊打開視頻講解更加詳細
盡管存在 prop 和事件,有的時候你仍可能需要在 JavaScript 里直接訪問一個子組件,為了達到這個目的,你可以通過 ref 這個 attribute 為子組件賦予一個 ID 參考,
<template>
<div id="app">
<HelloWorld ref="refChild"></HelloWorld>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
data(){
return {
}
},
created(){
console.log(this.$refs.refChild) //undefined Dom模板未渲染完成
},
mounted(){
console.log(this.$refs.refChild)
console.log(this.$refs.refChild.data)
console.log(this.$refs.refChild.change())
},
components:{
HelloWorld
},
computed:{
},
methods:{
}
}
</script>
<style scoped>
</style>
src\components\HelloWorld.vue
<template>
<div >
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: [],
data(){
return{
data:'子組件'
}
},
mounted(){
},
methods:{
change(){
console.log('5555')
}
}
}
</script>
<style scoped>
</style>
當 ref 和 v-for 一起使用的時候,你得到的 ref 將會是一個包含了對應資料源的這些子組件的陣列,
注意:$refs 只會在組件渲染完成之后生效,并且它們不是回應式的,這僅作為一個用于直接操作子組件的“逃生艙”——你應該避免在模板或計算屬性中訪問 $refs,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/502151.html
標籤:其他
