VUE中 ref $refs 使用详解,扩展到$parent 、$children 的使用
生活随笔
收集整理的這篇文章主要介紹了
VUE中 ref $refs 使用详解,扩展到$parent 、$children 的使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
$refs 的使用方法就是在元素或組件標簽上添加ref屬性指定一個引用信息,引用信息將會注冊在父組件的$refs對象上,在js中使用$refs來指向DOM元素或組件實例;
?
應用一:在DOM元素上使用$refs可以迅速進行dom定位,類似于$("selectId"),如下
? <template><div class="parent"><p ref="testTxt">{{oldMsg}}</p><button @click="changeMsg()">點擊修改段落內容</button></div></template><script>export default {data(){return {oldMsg:'這是原有段落數據內容',newMsg:'hello,這是新的段落數據內容!!',}},methods:{changeMsg(){this.$refs.testTxt.innerHTML=this.newMsg;},}}</script>??
應用二:也能在組件上使用ref屬性,可以通過$refs實現對子組件操作,如下
①使用this.$refs.paramsName能更快的獲取操作子組件屬性值或函數
parentone.vue 如下:
<template><div class="parent"><Childone ref="childItemId"></Childone><p style="color:blue;">{{msgFromChild}}</p><button @click="getChildMsg()">使用$refs獲取子組件的數據</button></div> </template><script> import Childone from './childone' export default {components:{Childone},data(){return {msgFromChild:'',}},methods:{getChildMsg(){this.msgFromChild=this.$refs.childItemId.childMsg;},} } </script>childone.vue 如下:
<template><div class="child"></div> </template><script> export default {data(){return {childMsg:'這是子組件的參數'}} } </script>?
擴展到$parent 、$children的使用:
②我們可以使用$children[i].paramsName 來獲取某個子組件的屬性值或函數,$children返回的是一個子組件數組
這里就只寫父組件的代碼了,parentone.vue如下:
<template><div class="parent"><Childone></Childone><Childtwo></Childtwo><p style="color:blue;">{{msgFromChild}}</p><button @click="getChildMsg()">使用$children來獲取子組件的數據</button></div> </template><script> import Childone from './childone' import Childtwo from './childtwo' export default {components:{Childone,Childtwo},data(){return {msgFromChild:'',}},methods:{getChildMsg(){this.msgFromChild=this.$children[1].child2Msg;},} } </script>?
③那么子組件怎么獲取修改父組件的數據內容?這需要使用$parent
parentone.vue如下
<template><div class="parent"><Childone></Childone></div> </template><script> import Childone from './childone' export default {components:{Childone},data(){return {parentMsg:'這是父組件的數據',}} } </script>childone.vue如下:
<template><div class="child"><p style="color:red;">{{msgFromParent}}</p><button @click="getParentMsg()">點擊使用$refs獲取父組件的數據</button></div> </template><script> export default {data(){return {msgFromParent:''}},methods:{getParentMsg(){this.$parent.parentMsg="子組件中可以修改父組件的內容,這是通過子組件修改所得"this.msgFromParent=this.$parent.parentMsg;}} } </script>?
注意:
· 當使用v-for的元素或組件,引用信息$refs將是包含DOM節點的或組件實例的數組,類似$children的使用;
· 注意?$refs不能在created生命周期中使用?因為在組件創建時候?該ref還沒有綁定元素
created(){//報錯, $refs不能在created生命周期中使用 因為在組件創建時候 該ref還沒有綁定元素this.changeMsg(); },methods:{changeMsg(){this.$refs.testTxt.innerHTML=this.newMsg;},}· 它是非響應的,所以應該避免在模板或計算屬性中使用?$refs ,它僅僅是一個直接操作子組件的應急方案;
總結
以上是生活随笔為你收集整理的VUE中 ref $refs 使用详解,扩展到$parent 、$children 的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Python】如何用Python实现W
- 下一篇: 【Python】Pandas 数据类型概