ref其他的API
# unRef和isRef
<script>
import { reactive, ref, unref, isRef, toRefs } from "vue";
export default {
setup(props, { attrs, slots, emit }) {
let NumOne = ref(0);
let NumTwo = 0;
const { name, age } = toRefs({ name: "xu", age: 20 });
const obj = {
name: "xu",
age: "20",
};
callback(NumOne, NumTwo, name, obj);
function callback(NumOne, NumTwo, name) {
console.log(isRef(NumOne)); // 返回true
console.log(isRef(NumTwo)); // 返回false
console.log(unref(name)); // 返回 xu
console.log(unref(obj)); // 返回 对象本身
}
// unref(val) 的原理
// val = isRef(val) ? val.value : val;
},
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# shallowRef和triggerRef
<template>
<div>
{{obj.name}}
{{ obj.lists[0].name }}
<button @click="BtnClick">点击修改</button>
</div>
</template>
<script>
import { ref, shallowRef ,triggerRef} from "vue";
export default {
setup(props, { attrs, slots, emit }) {
const obj = shallowRef({
name: "徐涛",
lists: [
{
age: "12",
name: "张山",
},
],
});
const BtnClick = () => {
obj.value.name="李四"
obj.value.lists[0].name = "22";
triggerRef(obj) // 当用到了 triggerRef 那么就会触发 shallowRef相关联的副作用
};
return {
obj,
BtnClick,
};
},
};
</script>
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
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