Reactive与Ref响应式数据的学习
#reactive #ref
Reactive与Ref响应式数据的学习的笔记
Reactive
Ref
Ref自动解包
readOnly
判断Reactive Api
Ref api
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
| <template> <div> <h1>toRefs api 的使用</h1> <div>{{ name }}-{{ age }}</div> <div>{{ name1 }}</div> <button @click="changeInfo">修改信息</button> </div> </template>
<script> import { reactive, toRefs, toRef } from 'vue'
export default { setup() { const info = reactive({ name: 'Hbisedm', age: 23, }) // 1. toRefs() 将对象的所有属性转换为 ref 对象 const { name, age } = toRefs(info)
const name1 = toRef(info, 'name') const changeInfo = () => { name.value = 'CoderSam' age.value = 24 }
return { name, name1, age, changeInfo } } } </script>
|
customRef
自定义ref
- track 用于收集依赖
- trigger 用于触发更新
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import { customRef } from "vue";
export default function (value, delay = 200) { let timeout = null; return customRef((track, trigger) => { return { get() { track(); return value; }, set(newValue) { clearTimeout(timeout); timeout = setTimeout(() => { value = newValue; trigger(); }, delay); }, }; }); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <template> <div> <h1>custom-ref-vue-study</h1> <input v-model="debounceRef" /> <p>{{ debounceRef }}</p> </div> </template>
<script> import useDebounceRef from '../../hook/useDebounceRef' export default { setup() { const debounceRef = useDebounceRef('123') return { debounceRef } } } </script>
|