Vue中ref和$refs的介紹以及使用方法示例
阿新 • • 發佈:2021-01-14
前言
在JavaScript中需要通過document.querySelector("#demo")來獲取dom節點,然後再獲取這個節點的值。在Vue中,我們不用獲取dom節點,元素繫結ref之後,直接通過this.$refs即可呼叫,這樣可以減少獲取dom節點的消耗。
ref介紹
ref被用來給元素或子元件註冊引用資訊。引用資訊將會註冊在父元件的 $refs物件上。如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子元件上,引用就指向該子元件例項
通俗的講,ref特性就是為元素或子元件賦予一個ID引用,通過this.$refs.refName來訪問元素或子元件的例項
<p ref="p">Hello</p> <children ref="children"></children>
this.$refs.p this.$refs.children
this.$refs介紹
this.$refs是一個物件,持有當前元件中註冊過 ref特性的所有 DOM 元素和子元件例項
注意: $refs只有在元件渲染完成後才填充,在初始渲染的時候不能訪問它們,並且它是非響應式的,因此不能用它在模板中做資料繫結
注意:
當ref和v-for一起使用時,獲取到的引用將會是一個數組,包含迴圈陣列源
<template> <div> <div ref="myDiv" v-for="(item,index) in arr" :key="index">{{item}}</div> </div> </template> <script> export default { data() { return { arr: ['one','two','three','four'] } },mounted() { console.log(this.$refs.myDiv) },methods: {} } </script> <style lang="sass" scoped> </style>
例項(通過ref特性呼叫子元件的方法)
【1】子元件code:
<template> <div>{{msg}}</div> </template> <script> export default { data() { return { msg: '我是子元件' } },methods: { changeMsg() { this.msg = '變身' } } } </script> <style lang="sass" scoped></style>
【2】父元件code:
<template> <div @click="parentMethod"> <children ref="children"></children> </div> </template> <script> import children from 'components/children.vue' export default { components: { children },data() { return {} },methods: { parentMethod() { this.$refs.children //返回一個物件 this.$refs.children.changeMsg() // 呼叫children的changeMsg方法 } } } </script> <style lang="sass" scoped></style>
總結
到此這篇關於Vue中ref和$refs的介紹以及使用的文章就介紹到這了,更多相關Vue中ref和$refs使用內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!