一谈截、動態(tài)獲取ref
ref是不會動態(tài)渲染的,所以當(dāng)你把ref用在數(shù)組上時(shí)涧偷,并且數(shù)組可以動態(tài)增減時(shí)簸喂,只能獲取到數(shù)組第一項(xiàng)各屬性的ref,但是后來動態(tài)添加的各項(xiàng)屬性獲取不到燎潮。
解決辦法
通過key來標(biāo)志組件不同喻鳄,來重新渲染頁面,以獲取新的ref
<el-table :key="randomValue" :data="list">
<el-table-column label="序號" align="center" border>
<template slot-scope="scope">
<span>{{scope.$index+1}}</span>
</template>
</el-table-column>
<el-table-column label="責(zé)任人" align="center" border>
<template slot-scope="scope">
<three-component
:ref="'duty'+scope.$index"
@change="changeMethod($event, scope.$index)"
>
</three-component>
</template>
</el-table-column>
<el-table-column label="操作" align="center" border>
<template slot-scope="scope">
<el-button type="primary" size="mini" @click="addRow">+<el-button>
</template>
</el-table-column>
</el-table>
data () {
return {
list:[{ person: '' }]
}
},
methods: {
addRow () {
this.list.push({ person: '' })
this.randomValue = Math.random()
},
changeMethod (val, index) {
let tempRef = 'duty' + index
let res = this.$refs[tempRef].getInfo()
}
}
二确封、父組件獲取子組件數(shù)據(jù)和方法
通過給子組件標(biāo)記ref來獲取子組件的數(shù)據(jù)和方法
<child ref="refChild"></child>
this.$refs.refChild.數(shù)據(jù)
this.$refs.refChild.方法
vue-ref補(bǔ)充
一除呵、用法
ref
被用來給元素或子組件注冊引用信息。引用信息將會注冊在父組件的 $refs
對象上爪喘。
如果在普通的 DOM 元素上使用颜曾,引用指向的就是 DOM 元素;
如果用在子組件上秉剑,引用就指向組件實(shí)例
<!-- `vm.$refs.p` will be the DOM node -->
<p ref="p">hello</p>
<!-- `vm.$refs.child` will be the child component instance -->
<child-component ref="child"></child-component>
二泛豪、注意事項(xiàng)
1、關(guān)于 ref 注冊時(shí)間的重要說明:因?yàn)?ref 本身是作為渲染結(jié)果被創(chuàng)建的侦鹏,在初始渲染的時(shí)候你不能訪問它們 - 它們還不存在诡曙!
所以可以在mounted
鉤子或this.$nextTick(()=>{})
中調(diào)用
2、$refs
也不是響應(yīng)式的略水,因此你不應(yīng)該試圖用它在模板中做數(shù)據(jù)綁定价卤。
更改后,可以嘗試使用key來刷新