Vue-Challenges

Vue-Challenges

2. ref 全家桶

https://github.com/webfansplz/vuejs-challenges/blob/main/questions/2-ref-family/README.zh-CN.md

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<script setup lang="ts">
import { ref, Ref, reactive, isRef, unref, toRef } from "vue"

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

// Challenge 1: Update ref
function update(value) {
count.value = value
}

/**
* Challenge 2: Check if the `count` is a ref object.
* Make the output be 1
*/
console.log(isRef(count) ? 1 : 0)

/**
* Challenge 3: Unwrap ref
* Make the output be true
*/
function initialCount(value: number | Ref<number>) {
// Make the output be true
console.log(unref(value) === 10)
}

initialCount(initial)

/**
* Challenge 4:
* create a ref for a property on a source reactive object.
* The created ref is synced with its source property:
* mutating the source property will update the ref, and vice-versa.
* Make the output be true
*/
const state = reactive({
foo: 1,
bar: 2,
})
const fooRef = toRef(state, 'foo') // change the impl...

// mutating the ref updates the original
fooRef.value++
console.log(state.foo === 2)

// mutating the original also updates the ref
state.foo++
console.log(fooRef.value === 3)

</script>

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

  • isRef
  • unref
  • toRef