-
递归监听
Vue3.X是通过ES6的
Proxy
实现数据的双向绑定(即只有包装成Proxy
的数据才会主动更新视图),即它会把ref
和reactive
的所有子节点包装成Proxy
并进行视图更新,因此,如果数据量过大,递归监听会非常消耗性能,例:<template> <ul> <li>{{ test.a }}</li> <li>{{ test.gf.b }}</li> <li>{{ test.gf.f.c }}</li> <li>{{ test.gf.f.s.d }}</li> </ul> <button @click="changeToNum">测试递归监听</button> </template>
setup() { // let test = reactive({ let test = ref({ a: 'a', gf: { b: 'b', f: { c: 'c', s: { d: 'd' } } } }); function changeToNum() { // test.a = '1'; // test.gf.b = '2'; // test.gf.f.c = '3'; // test.gf.f.s.d = '4'; // console.log(test); // console.log(test.gf); // console.log(test.gf.f); // console.log(test.gf.f.s); test.value.a = '1'; test.value.gf.b = '2'; test.value.gf.f.c = '3'; test.value.gf.f.s.d = '4'; console.log(test); console.log(test.value); console.log(test.value.gf); console.log(test.value.gf.f); console.log(test.value.gf.f.s); } return {test, changeToNum}; }
-
非递归监听
非递归监听只能监听第一层的数据变化,主要用到的方法有
shallowReactive
shallowRef
和triggerRef
-
shallowReactive
会把reactive
类型的数据的第一层包装成Proxy
,因此如果更新了数据的第一层,视图会主动更新,例:import {shallowReactive} from 'vue'; export default { name: 'App2', setup() { let state = shallowReactive({ a: 'a', gf: { b: 'b', f: { c: 'c', s: { d: 'd' } } } }); function changeToNum() { state.a = '1'; //如果注释这一句,视图将不会主动更新 state.gf.b = '2'; ... console.log(state); console.log(state.gf); ... } return {state, changeToNum}; } }
-
shallowRef
会把.value
包装成Proxy
(类比ref(10)
的实质是reactive({ value: 10})
),所以如果想更新视图,则要更新value
,例:import {shallowRef} from 'vue'; export default { name: 'App2', setup() { let state = shallowRef({ a: 'a', gf: { b: 'b', f: { c: 'c', s: { d: 'd' } } } }); function changeToNum() { state.value = { a: '1', gf: { b: 'b', f: { c: 'c', s: { d: 'd' } } } }; // state.value.a = '1' // 这样写视图不会更新 state.value.gf.b = '2'; ... console.log(state); console.log(state.value); ... } return {state, changeToNum}; } }
-
triggerRef
是Vue 3.X提供的单独更新数据类型为ref
的某一项数据的方法,要注意的是,Vue3.X只提供了triggerRef
,没有提供triggerReactive
,所以reactive
类型数据无法主动更新页面,例:import {ref,triggerRef} from 'vue'; export default { name: 'App2', setup() { let state = ref({ a: 'a', gf: { b: 'b', f: { c: 'c', s: { d: 'd' } } } }); function changeToNum() { state.value.gf.f.s.d = '4'; triggerRef(state); } return {state, changeToNum}; } }
-
-
应用场景
- 一般情况下用
ref
和reactive
进行递归监听即可 - 只有当数据量特别大的时候才采用非递归监听
- 一般情况下用
目录:VUE3.X笔记——目录
上一篇:VUE3.X——Composition API
下一篇:VUE3.X——响应数据原理