vue3-to

7/18/2020 vue3

# toRef


注意:如果原始对象是非响应式的就不会更新视图 数据是会变的,如果原始对象是响应式的是会更新视图并且改变数据的

  • 针对一个响应式对象(reactive)的prop
  • 创建一个ref,具有响应式
  • 两者保持引用关系

没有使用toRef

<script setup lang="ts">
import { reactive } from 'vue';
let obj = reactive({
  a: 1,
  b: 2
})

const handleClick = () => {
  obj.a ++ 
  console.log(obj); 
}

</script>

<template>
  <div>
    {{obj}}
    <button @click="handleClick">更新</button>
  </div>
</template>

<style scoped>
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

使用了toRef

<script setup lang="ts">
import { reactive , toRef } from 'vue';
let obj = reactive({
  a: 1,
  b: 2
})

let newObj = toRef(obj, "a") // 将a 转化为响应式对象
console.log(newObj);

const handleClick = () => {
  newObj.value ++ 
  console.log(obj, newObj); 
}

</script>

<template>
  <div>
    {{newObj}}
    <button @click="handleClick">更新</button>
  </div>
</template>

<style scoped>
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

# toRefs -- setup中返回toRefs(state)


转换为ref 可以在不失去响应性的情况下进行解构

  • 将响应式对象(reactive封装)转换为普通对象
  • 对象的每个prop都是对应的ref
  • 两者保持引用关系
<script setup lang="ts">
import { reactive , toRefs } from 'vue';
let obj = reactive({
  a: 1,
  b: 2
})

const { a, b } = toRefs(obj) // 转换为ref 可以在不失去响应性的情况下解构
a.value ++ 
console.log(a, b);

</script>

<template>
  <div>
   
  </div>
</template>

<style scoped>
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<template>
    <div>
        toRefs --- {{ name }} --- {{ age }}
    </div>
</template>
 
<script setup lang="ts">
import { toRefs, reactive } from 'vue';
function useFeature() {
    let state = reactive({
        name: 'dsf',
        age: 20
    })
    // 返回时转换为ref
    return toRefs(state)
}
// 可以在不失去响应性的情况下解构
const {name, age} = useFeature()
</script>
<style>
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 为什么需要toRef 和 toRefs

  • 不丢失响应式的情况下,把对象的数据分解、或者扩散(解构)
  • 针对响应式对象(reactive包裹的),非普通对象
  • 是对响应式的一种延续和关联或者引用,不是创造

# toRaw


将响应式对象转化为普通对象

<script setup lang="ts">
import { reactive , toRaw } from 'vue';
let obj = reactive({
  a: 1,
  b: 2
})

let newObj = toRaw(obj)
console.log(newObj); // {a: 1, b: 2}

</script>

<template>
  <div>
   
  </div>
</template>

<style scoped>
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
更新: 7/25/2022, 3:15:19 PM