久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

Vue中ref和$refs的介紹以及使用方法示例

瀏覽:37日期:2022-10-11 16:27:01
前言

在JavaScript中需要通過document.querySelector('#demo')來獲取dom節(jié)點,然后再獲取這個節(jié)點的值。在Vue中,我們不用獲取dom節(jié)點,元素綁定ref之后,直接通過this.$refs即可調(diào)用,這樣可以減少獲取dom節(jié)點的消耗。

ref介紹

ref被用來給元素或子組件注冊引用信息。引用信息將會注冊在父組件的 $refs對象上。如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子組件上,引用就指向該子組件實例

通俗的講,ref特性就是為元素或子組件賦予一個ID引用,通過this.$refs.refName來訪問元素或子組件的實例

<p ref='p'>Hello</p><children ref='children'></children>

this.$refs.pthis.$refs.childrenthis.$refs介紹

this.$refs是一個對象,持有當(dāng)前組件中注冊過 ref特性的所有 DOM 元素和子組件實例

注意: $refs只有在組件渲染完成后才填充,在初始渲染的時候不能訪問它們,并且它是非響應(yīng)式的,因此不能用它在模板中做數(shù)據(jù)綁定

注意:

當(dāng)ref和v-for一起使用時,獲取到的引用將會是一個數(shù)組,包含循環(huán)數(shù)組源

<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>

Vue中ref和$refs的介紹以及使用方法示例

實例(通過ref特性調(diào)用子組件的方法)

【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() // 調(diào)用children的changeMsg方法 } }}</script> <style lang='sass' scoped></style>總結(jié)

到此這篇關(guān)于Vue中ref和$refs的介紹以及使用的文章就介紹到這了,更多相關(guān)Vue中ref和$refs使用內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Vue
相關(guān)文章:
主站蜘蛛池模板: 固镇县| 阜康市| 治县。| 日照市| 武夷山市| 余姚市| 大同市| 英吉沙县| 孝昌县| 无棣县| 徐州市| 镇雄县| 永善县| 永昌县| 婺源县| 肇庆市| 正定县| 洮南市| 南充市| 和龙市| 安阳县| 涟源市| 资中县| 泸溪县| 京山县| 固始县| 双峰县| 团风县| 鹤山市| 宿松县| 陵川县| 长治市| 平罗县| 阳新县| 桃源县| 柯坪县| 阳西县| 广昌县| 永济市| 桓台县| 咸阳市|