1、引入vue文件报错(因为velur插件)
问题:
image.png
解决:
image.png
取消选中后关闭文件,推荐使用volar插件
2、reactive 直接赋值后失去响应式
如果reactive 是个数组
const arr = reactive([])
arr.length=0
arr.push(...new Array)
如果是个对象
Object.assign(formState,res.data)
或者多嵌套一层
let a=reactive({a:{id:1,name:'小明'}})
3、toRaw、markRaw 、 toRef 和 toRefs 的作用、用法、区别
1、
toRaw 将响应式对象转化为普通对象
markRaw 使用markRaw包裹之后的对象,永远不能转成响应式数据,即使使用ref包裹。页面不会发生改变
注意点:前提不先使用 reactive 包裹
2、
toRef 和 toRefs 可以用来复制 reactive 里面的属性然后转成 ref,而且它既保留了响应式,也保留了引用,也就是你从 reactive 复制过来的属性进行修改后,除了视图会更新,原有 ractive 里面对应的值也会跟着更新,如果你知道 浅拷贝 的话那么这个引用就很好理解了,它复制的其实就是引用 + 响应式 ref
不加 s 和 加 s 的区别就是这样:
toRef: 复制 reactive 里的单个属性并转成 ref
toRefs: 复制 reactive 里的所有属性并转成 ref
3、
toRefs 可批量创建响应式数据。 直接结构出来的数据,是非响应式的数据,通过toRefs定义为响应式数据。
(不管是修改解构后的值,或者修改直接的赋的值,都会影响原来的reactive)
应用场景:解构赋值,避免重复定义响应式对象,直接引用使用reactive对象里的属性。
<template>
<h2>
reactive-info-greet: {{ info.greet }}
</h2>
// 要带上 .value
<h2>
toRefs-rInfo-greet: {{ rInfo.greet.value }}
</h2>
<button @click="onChangeGreet">更新</button>
</template>
<script>
import { reactive, toRefs } from 'vue'
export default {
setup() {
let info = reactive({
name: 'Tony',
greet: 'Hello'
})
// 复制整个 info
let rInfo = toRefs(info)
// 更改 rInfo.greet
const onChangeGreet = () => {
rInfo.greet.value = 'world!'
}
return {
info,
rInfo,
onChangeGreet
}
}
}
</script>
使用toRefs 直接赋值后(没有解构赋值):
template 要想访问 toRefs 的值,需要带上 .value 如果不带上,就会出现双引号。
template 要想访问 toRef 的值,不需要带上 .value
image.png