1. 原生js中我们会使用document.getElementsByClassName(),document.getElementById()等获取dom元素,但在vue中,更推荐使用ref获取。
2. 不同文件的ref相互独立,即使同名也不会互相影响而导致获取错误。一个组件被多次引用后同时存在多个实例时,每个实例的ref也是互相独立的。这一点显然比getElementById()要好很多。
3. 标签的ref属性值在每一个vue文件中需要是唯一的,否则可能在获取时发生与预期不同的效果。显然使用v-for时如果单项带有ref就需要我们解决这个问题。
目录
使用ref绑定Dom元素
- 用法相当简单,我们在想获取的标签上增加属性 ref="refName" 即可。
- 例如:
<template>
<span id="myspanid" ref="mySpanRef">hello coolight</span>
</template>
获取
获取的方式很多,这里介绍其中的几种,以及提及一些document的方法和注意事项
祖传getElementById()
- 在vue中,getElementById()依然可用,但不建议,而且要注意生命周期问题
<script setup>
import { onMounted } from "vue";
let span_id = document.getElementById("myspanid");
console.log("setup: span_id = ", span_id);
onMounted(() => {
console.log("onMounted: span_id = ", span_id);
span_id = document.getElementById("myspanid");
console.log("onMounted: span_id = ", span_id);
})
</script>
<template>
<span id="myspanid" ref="mySpanRef">hello coolight</span>
</template>
- 运行结果:
- 可以看到,在setup中直接使用getElementById()是不行的,需要在onMounted(也就是已经把dom元素挂载完成后)重新调用getElementById()获取。
- 这就是vue的生命周期问题,贴一张vue官网的图,具体有关生命周期的在此不展开讲了:
ref(null)
- refName = ref(null)是常见的获取方法
- 即声明一个与在标签中ref元素值同名的变量,然后调用ref(null)即可获取到。
- 注意需要导入:import { ref } from "vue";
- 示例:
<script setup>
import { ref,onMounted, getCurrentInstance } from "vue";
let mySpanRef = ref(null);
console.log("setup: mySpanRef = ", mySpanRef);
console.log("setup: mySpanRef.value = ", mySpanRef.value);
onMounted(() => {
console.log("读取setup获取的mySpanRef:");
console.log("onMounted: mySpanRef = ", mySpanRef);
console.log("onMounted: mySpanRef.value = ", mySpanRef.value);
mySpanRef = ref(null);
console.log("读取onMounted获取的mySpanRef:");
console.log("onMounted: mySpanRef = ", mySpanRef);
console.log("onMounted: mySpanRef.value = ", mySpanRef.value);
})
</script>
<template>
<span ref="mySpanRef">hello coolight</span>
</template>
- 运行结果:
- 可以看到 ref(null) 返回的是一个 RefImpl 对象,如果想它打印结果和getElementById()一样,则需要 .value。如果我们想调用元素的操作方法等,也需要.value后再接操作方法。
- 比如:
<script setup>
import { ref, onMounted } from "vue";
const mySpanRef = ref(null);
onMounted(() => {
console.log(mySpanRef);
console.log(mySpanRef.clientWidth);
console.log(mySpanRef.value.clientWidth);
})
</script>
<template>
<span ref="mySpanRef">hello coolight</span>
</template>
- 运行结果:
- 显然,使用ref(null)获取的也会有生命周期问题,但这次仅仅是mySpanRef.value = null。
- 而且我们要注意应在setup中调用ref(null)获取,但在onMounted以后才能访问其.value,进行dom相关的函数调用操作。
- 如果在onMounted内调用ref(null)获取反而获取不到。
$refs.refName
- 这个方法则不需要变量名和ref值相同
- 注意:
- 需要在onMounted后获取
- 需要导入getCurrentInstance()
- 如果在setup直接调用了getCurrentInstance(),将导致在onMounted()中获取失败。
- 示例:
<script setup>
import { onMounted, getCurrentInstance } from "vue";
let mySpan;
onMounted(() => {
let { $refs } = (getCurrentInstance()).proxy;
mySpan = $refs.mySpanRef;
console.log("onMounted: mySpan = ", mySpan);
})
</script>
<template>
<span ref="mySpanRef">hello coolight</span>
</template>
- 运行结果:
- 如你所见,返回和getElementById()一样,我们可以直接调用dom标签的方法而不需要像ref(null)获取后.value。
$refs[refName]
- 前面我们介绍的都是需要将refName当成变量名一样写,而不能使用字符串。
- 这个方法可以传refName的字符串类型,这将大大提高我们获取的灵活度,而且它也不限制接收的变量名。
- 示例:
<script setup>
import { onMounted, getCurrentInstance } from "vue";
let mySpan;
onMounted(() => {
let { $refs } = (getCurrentInstance()).proxy;
let name = "mySpanRef";
mySpan = $refs[name];
//mySpan = $refs['mySpanRef']; //这个也是可以的
console.log("onMounted: mySpan = ", mySpan);
})
</script>
<template>
<span ref="mySpanRef">hello coolight</span>
</template>
- 运行结果:
- 其返回值同$refs.refName。
多个同名ref的解决方法
上面我们都是把ref当成id一样使用,但在v-for后产生的列表项可能遇到ref重复,下面我们聊聊如何解决这个问题
- 首先我们来看看如果ref重复,我们获取时会发生什么:
- 示例:
<script setup>
import { ref, onMounted, getCurrentInstance } from "vue";
let mySpanRef = ref(null);
onMounted(() => {
console.log("ref(null) = ", mySpanRef.value);
let { $refs } = (getCurrentInstance()).proxy;
mySpanRef = $refs.mySpanRef;
console.log("$refs.mySpanRef = ", mySpanRef);
mySpanRef = $refs['mySpanRef'];
console.log("$refs['mySpanRef'] = ", mySpanRef);
})
</script>
<template>
<div>
<span ref="mySpanRef">hello coolight</span>
<span ref="mySpanRef">hello 洛天依</span>
</div>
</template>
- 运行结果:
- 可以看到,三个方法都是得到了后一个拥有这个refName的标签
- 虽然没有报错或是警告,但已经不是预期的效果了(按平常感觉应返回一个数组)
- 解决思路:
- 我们需要改造,使得ref仍然是唯一的。
- 那么我们可以给这些同名的ref标签在refName后面再加一个id,就可以使得refName是唯一
- 显然我们需要利用第三种获取方法($refs['refName']),并用字符串拼接来生成refName
- 示例:
<script setup>
import { onMounted, getCurrentInstance } from "vue";
let arr = ['coolight', '洛天依', 'enter', 'shift', 'ctrl', 'Alt', 'ESC'];
onMounted(() => {
let { $refs } = (getCurrentInstance()).proxy;
console.log($refs['myspan0']);
console.log("for:");
for(let i = arr.length; i-- > 0;) {
console.log($refs['myspan'+ i][0]);
}
})
</script>
<template>
<div style="display:flex;flex-direction: column;">
<span v-for="(item, index) in arr"
:ref="'myspan' + index">{{index}}:{{item}}</span>
</div>
</template>
- 运行结果:
- 可以看到,这一次$refs['refName']返回的是一个包含一个span标签的数组,因此我们需要后面再加[0]访问数组内容。
其他问题
返回的是一个proxy对象
- 当返回的是proxy对象时,它的$el属性就是我们需要的标签
- 示例:
let { $refs } = (getCurrentInstance()).proxy;
let dom = $refs['myul']; //proxy对象
dom.$el; //标签内容
dom.$el.clientWidth; //通过$el即可同getElementById()获取到的标签一样操作
https://furpharm.com/# lasix
I love it when individuals get together and share views. Great website, keep it up.
https://gabapharm.com/# cheapest Gabapentin GabaPharm
The next time I read a blog, Hopefully it won’t disappoint me as much as this one. After all, I know it was my choice to read through, nonetheless I genuinely believed you’d have something helpful to talk about. All I hear is a bunch of whining about something you could possibly fix if you weren’t too busy seeking attention.
Тут можно преобрести оружейные сейфы и шкафы сейф для сайги 12
buy gabapentin: Buy gabapentin for humans – gabapentin
https://furpharm.com/# cheapest lasix
https://erepharm.com/# ere pharm
Can I just say what a relief to find somebody who genuinely understands what they are talking about online. You actually know how to bring a problem to light and make it important. A lot more people must check this out and understand this side of the story. It’s surprising you are not more popular since you surely possess the gift.
Nancy Prentice. For services to the Group in Mid-Glamorgan.
By the late nineteenth century statues had been installed on the esplanade on the northern facet while the streets to the south past Parker Street had been narrow.
My Tattershall Castle one got caught up with a bath towel a number of years ago and one small rip has meant the edges proceed to fray every time that it is washed.
The original design was adapted for numerous applications for use in the 1985 enchantment, each 2D graphics and three-dimensional objects.
Nevertheless, it incurs additional operating prices for amassing every materials, and requires intensive public education to avoid recyclate contamination.
This menagerie craft can isolate modifiers, within the case of getting 3 suffixes, splitting the item will consequence in one copy having 1 suffix, and the opposite having 2, one of many suffixes we’d like shall be assured, however it is a 50/50 to get each suffixes as properly as the open modifier.
Billie Piper continued her function as companion Rose Tyler, for her second and final sequence.
Why we love this game: Truthfully, just because you’ll be able to play it with out utilizing your head a lot, and it all the time creates good laughs as somebody will at all times choose bizarre choices.
In these days, between the personal, nonprofit environmental groups and the world of teams representing business agriculture, collaboration was largely absent.
Ackerman famous that the building ordinance would enable a proper building with masonry partitions over a frame station and reiterated that the rules allow town to power the railroad to do what they need.
Major (now Lieutenant-Colonel) (Technical Officer, Telecommunications) Holroyd Ernest Hugh Clements (105592), Royal Corps of Signals.
The lot rent price and mobile residence park expenses could be slightly troublesome to grasp at first.
buy rybelsus online usa buy rybelsus rybpharm rybpharm cheap semaglutide
Each gem, be it the Manikya, pearl, emerald, or another stone, has its own distinctive options.
Group Captain James Douglas Melvin, OBE.
Just like The Resistance on a surface degree, in Secret Hitler governments take the place of missions, and liberal and fascist policies change successes and failures.
You enter the sphere once, you do all three phases, and then you are executed.
cheapest lasix: buy lasix fur pharm – lasix
https://rybpharm.com/# buy rybelsus rybpharm
The ride is positioned at each Universal Studios Florida and Universal Studios Hollywood in the previous Back to the future: The Journey buildings at each locations.
Grey, Christopher (September 15, 1996).
Lighting specialists plan gentle in very technical terms utilizing site-particular mathematical equations to attain their results.
Utilizing your nursery crib bedding colors for your foundation will set you in the proper route for the remainder of your decorating needs.
UK – Mid-market private fairness investor LDC has backed the administration buyout (MBO) of Martin Audio, the designer and producer of premium high-efficiency loudspeaker systems, from global audio specialist Loud Audio.
Selwyn Victor Jones, of Point Piper, New South Wales.
“Family farms are just the bottom of the pyramid.
Hobart additionally requested extra particulars from Schneider to offer after the listening to, to Weinberger’s displeasure, noting it was one other delay tactic.
This got here after Wilson cited a regulation from 1873 that at the least four justices (three affiliate and the chief justice) can be required to have the hearing.
Hezekiah Nyaga s/o Njeroge, 1st Grade Tribal Police Constable, Kenya.
Здесь можно преобрести где купить сейф сейф купить в москве
On August 1, 2017, the city Council voted to adopt the ordinance.
Its founder James Melville instructed DeSmog that the marketing campaign, which claims to represent the voices of farmers, plans to target nationwide and native legislation on points like pricing and meals safety as well as “aspects of internet zero”.
You might also get the extra quantity in your subsequent cost in the event you have been assessed as having LCW or LCWRA as part of an ESA declare and also you had been on a ‘credit score-only claim’ while you claimed Common Credit.
Ask for waterfall layers and a rounded perimeter.
The Duchess of Sussex has made headlines along with her dazzling royal tour wardrobe – but her range of hairstyles has been equally noteworthy.
It’s comforting understanding that the extra money is there for me to use in direction of an emergency fund or to go in direction of something special like a down payment on a house or sure, even a brand new car!
Andrew Hyslop Montgomery, Chief Superintendent, Staffordshire Police.
Bus Traces B (Johanesskirche to Haslach Englerplatz) and C (Johanneskirche to St.
Osborn could not get by means of the door to the aflame ready room.
Step 3: Using white paint, paint a smaller circle (the snowman’s head) resting on top of the bottom circle.
I really like it when people get together and share ideas. Great website, stick with it.