Vue 笔记 04-Vue3 利用 ref 函数获取 dom 元素内容

警告
本文最后更新于 2024-05-18,文中内容可能已过时。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<script setup lang="ts">
import { ref } from 'vue'
const dom = ref<HTMLDivElement>()
function change() {
  console.log(dom.value?.innerText)
}
</script>
<template>
  <div>
    <button @click="change">change</button>
    <div ref="dom">Hello Meowrain</div>
  </div>
</template>
<style></style>

在元素上添加 ref="变量名",script 中写 const dom = ref<HTMLDivElement>(),因为采用了 setup 语法糖,如果直接写在 script 标签中,得到的结果就是 undefined, 只有在函数中才能调用. https://blog.meowrain.cn/api/i/2024/01/21/xaqpp7-3.webp


问题:vue3 中 reactive 对象赋值,不能响应式变化

在使用 vue3 中,使用 reactive 创建的对象或者数组进行赋值时,可以正常赋值,但是不会触发响应式变化。

例子:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<script setup lang="ts">
import { ref,reactive } from 'vue'
let list = reactive<string[]>([]);
let obj = reactive({});
function add(){
    setTimeout(()=>{
        obj = {
            name:'meowrain',
            age:20
        }
        console.log(obj);
    },2000)
}
</script>
<template>
  <div>
    <button @click="add">add</button>
    
    <div>{{ obj }}</div>
  </div>
</template>
<style></style>

https://blog.meowrain.cn/api/i/2024/01/21/xph1o1-3.webp

我们按下按钮,等待 2 秒 https://blog.meowrain.cn/api/i/2024/01/21/xpnkmf-3.webp

可以看到 obj 的值已经发生了变化,但是页面没有进行渲染,与此同时,obj 的响应式对象被破坏 (本来应该是 Proxy(Object) {} 类型的,现在成了纯粹的普通对象了

解决办法

方法 1

直接添加对象的属性

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<script setup lang="ts">
import { ref,reactive } from 'vue'
let list = reactive<string[]>([]);

let obj = reactive({});
console.log(obj);
function add(){
    setTimeout(()=>{
        obj.name = 'meowrain'
        obj.age = '120'
        console.log(obj);
    },2000)
}
</script>
<template>
  <div>
    <button @click="add">add</button>
    
    <div>{{ obj }}</div>
  </div>
</template>
<style></style>

https://blog.meowrain.cn/api/i/2024/01/21/xslsdm-3.webp 按下按钮 https://blog.meowrain.cn/api/i/2024/01/21/xsozdk-3.webp

数组的话就是调用 push, 然后把异步获取的数据解构传入就行了

方法 2

使用 ref 不必多说,直接 ref 包起来给 xxx.value 赋值就行


相关内容

0%