vue3之toRef
- toRef是将对象中的某个值转化为响应式数据 toRef(obj,key)
toRef定义原始数据非响应式数据
- toRef 如果原始对象是非响应式的就不会更新视图 数据是会变的
<template>
<div>
<button @click="change">change</button>
<div>{{ obj }}</div>
</div>
</template>
<script setup lang="ts">
import { toRef, reactive } from 'vue'
const obj = {
num: 1,
count: 2,
}
let state = toRef(obj, 'num')
const change = () => {
state.value = 3
obj.count = 3
console.log('原始obj', obj)
console.log('引用state', state)
}
</script>
- 原始数据非响应式数据 效果
toRef定义原始数据为响应式数据
- toRef 如果原始对象是响应式时,原始数据,和copy的数据 都会产生影响,视图也发生变化
<template>
<div>
<button @click="change">change</button>
<div>{{ obj }}</div>
</div>
</template>
<script setup lang="ts">
import { toRef, reactive } from 'vue'
const obj = reactive({
num: 1,
})
let state = toRef(obj, 'num')
const change = () => {
state.value = 3
console.log('原始obj', obj)
console.log('引用state', state)
}
</script>
- 效果:
toRefs 可批量创建响应式数据
- 也就是对对象解构时,解构出来的值为非响应式数据,但使用 toRefs 定义后 这些被解构出来的值 为响应式数据
<template>
<div>
<button @click="change">change</button>
<div>{{ obj }}</div>
</div>
</template>
<script setup lang="ts">
import { toRefs, reactive } from 'vue'
const obj = reactive({
num: 1,
count: 2,
})
let { num, count } = obj
console.log('num', num, 'count', count)
let { num: num1, count: count1 } = toRefs(obj)
console.log('num1', num1, 'count1', count1)
const change = () => {
num = 10
count1.value = 100
console.log('事件num', num)
}
</script>
- 效果
toRaw
<template>
<div>
<button @click="change">change</button>
<div>{{ obj }}</div>
</div>
</template>
<script setup lang="ts">
import { toRaw, reactive } from 'vue'
const obj = reactive({
num: 1,
count: 2,
})
let newObj = toRaw(obj)
console.log('newObj', newObj)
const change = () => {
newObj.count = 33
console.log('newObj2', newObj)
}
</script>
- 效果
|