Skip to content

2 - ref 全家桶 #2303

Open
Open
@RanGuMo

Description

@RanGuMo

1.直接赋值即可

// 挑战 1: 更新 ref
function update(value) {
  count.value = value 
}

2. 用isRef(ref值) 判断是否为一个ref对象

/**
 * 挑战 2: 检查`count`是否为一个 ref 对象
 * 确保以下输出为1
*/
console.log(
  // impl ? 1 : 0
  isRef(count) ? 1 : 0
)

3. unref 目的是确保获取到的值是底层非代理的值

举个列子: 假设:a被ref代理了,const a = ref(1),那么我去取值就必须加上a.value 才能取到1, 如果用了unref(a), 那么a取到的值就是1。 如果a没有被ref代理(也没有被reactive代理),那么 unref 不会对其产生任何影响,它将直接返回该值,用 unref(a) a取到还是1。
简而言之, unref 目的是确保获取到的值是底层非代理的值。

/**
 * 挑战 3: 如果参数是一个 ref,则返回内部值,否则返回参数本身
 * 确保以下输出为true
*/
function initialCount(value: number | Ref<number>) {
  // 确保以下输出为true
  console.log(unref(value) === 10)
}

4.用toRef() 即可

toRef 函数接受两个参数:第一个参数是源对象,第二个参数是源对象的属性名。
toRefs 函数接受一个参数,该参数是一个响应式对象。它的主要作用是将一个包含响应式属性的对象转换为一个具有相同属性但每个属性都是独立的 ref 对象的对象。
举例:const state = reactive({
foo: 1,
bar: 2,
})
1.使用 toRefs const fooRef = toRefs(state)
2. 取值: fooRef.foot.value 和 fooRef.bar.value

/**
 * 挑战 4:
 * 为源响应式对象上的某个 `property` 新创建一个 `ref`。
 * 然后,`ref` 可以被传递,它会保持对其源`property`的响应式连接。
 * 确保以下输出为true
*/
const state = reactive({
  foo: 1,
  bar: 2,
})
const fooRef = toRef(state,'foo') // 修改这里的实现...

// 修改引用将更新原引用
fooRef.value++
console.log(state.foo === 2)

// 修改原引用也会更新`ref`
state.foo++
console.log(fooRef.value === 3)

5.完整答案

<script setup lang="ts">
import { ref, Ref,isRef,unref,toRef, reactive } from "vue"

const initial = ref(10)
const count = ref(0)

// 挑战 1: 更新 ref
function update(value) {
  // 实现...
  count.value = value
}

/**
 * 挑战 2: 检查`count`是否为一个 ref 对象
 * 确保以下输出为1
*/
console.log(
  // impl ? 1 : 0
  isRef(count) ? 1 : 0
)

/**
 * 挑战 3: 如果参数是一个 ref,则返回内部值,否则返回参数本身
 * 确保以下输出为true
*/
function initialCount(value: number | Ref<number>) {
  // 确保以下输出为true
  console.log(unref(value) === 10)
}

initialCount(initial)

/**
 * 挑战 4:
 * 为源响应式对象上的某个 `property` 新创建一个 `ref`。
 * 然后,`ref` 可以被传递,它会保持对其源`property`的响应式连接。
 * 确保以下输出为true
*/
const state = reactive({
  foo: 1,
  bar: 2,
})
const fooRef = toRef(state,'foo') // 修改这里的实现...

// 修改引用将更新原引用
fooRef.value++
console.log(state.foo === 2)

// 修改原引用也会更新`ref`
state.foo++
console.log(fooRef.value === 3)

</script>

<template>
  <div>
    <h1>msg</h1>
    <p>
      <span @click="update(count - 1)">-</span>
      {{ count }}
      <span @click="update(count + 1)">+</span>
    </p>
  </div>
</template>

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions