Vue中 ref、$refs區別與使用


 

 

定義2個組件:

子組件ChildrenSubRef.vue:

 1 <template>
 2   <div>
 3     
 4   </div>
 5 </template>
 6 
 7 <script>
 8 export default {
 9   name: "ChildrenSubRef",
10   data() {
11     return {
12       data1: {
13         a: 111,
14         b: 222
15       },
16       data2: {
17         c: 333,
18         d: 444
19       }
20     }
21   },
22   methods: {
23     getSub1() {
24       return this.$data
25     },
26     getSub2() {
27       console.log('執行子組件方法 getSub2')
28     }
29   }
30 }
31 </script>

 

父組件ParentDemoRefs.vue:

 1 <template>
 2   <div>
 3     <h2 @click="getRefB">getRefB</h2>
 4     <h2 @click="getRefB_func">getRefB_func</h2>
 5     <h2 @click="getRefB_Data">getRefB_Data</h2>
 6     <div ref="refA">hello</div>
 7     <ChildrenSubRef ref="refB"/>
 8   </div>
 9 </template>
10 
11 <script>
12 import ChildrenSubRef from "@/components/ChildrenSubRef.vue";
13 
14 export default {
15   name: "ParentDemoRefs",
16   components: {
17     ChildrenSubRef
18   },
19   methods: {
20 
21     getRefB() {
22       console.log(this.$refs.refB)
23     },
24     getRefB_func() {
25       this.$refs.refB.getSub2()
26     },
27     getRefB_Data() {
28       console.log(this.$refs.refB.getSub1())
29     }
30   }
31 };
32 </script>

 

ref:

我們可以給任意dom或組件附加上ref屬性

像這樣,只需要在標簽上機上屬性ref即可,名字可DIY

 

1 <div ref="refA">hello</div>
2 <ChildrenSubRef ref="refB"/>

 

$refs:

上面定義的一個或多個含有ref屬性的dom元素或組件,在當前組件實例化后會將它們寫入組件實例的屬性$refs,$refs是一個集合,

頁面有一個ref就有一個元素在里面,而實際上$refs里的每個ref都指向它的實例

 

 

訪問this.$refs.refA 就可以訪問到這個refA所在的dom:

<div>hello</div>

 

訪問this.$refs.refB 就可以訪問到這個refB所在的Vue組件實例:

 

  

在父組件能拿到子組件的實例,就像在子組件中訪問子組件實例一樣,那就明白ref能干嘛了

可以在父組件訪問子組件的數據或方法:

 

執行子組件方法:

this.$refs.refB.getSub1()

 

由此看來,$refs提供了訪問子組件的一種途徑,可以根據實際開發需要使用

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM