vue3语法糖

329 阅读2分钟

基础语法

1、ref, shallowRef, triggerRef

import {ref, shallowRef} from 'vue';
const name = ref('小满'); // 是响应式的数据,改变值的时候页面也会跟着变
const obj = shallowRef({
    name: '张三'
})
const changeObj = () => {
    obj.value.name = '李四'; // 通过这种方式是没有响应式的,它只对第一层有响应式
    obj.value = {name: '李四'}; // 这种写法具有响应式
}

但是如果配合 triggerRef 配合使用,也能使 shallowRef 的数据具有响应式

import {shallowRef, triggerRef} from 'vue';
const obj = shallowRef({
    name: '张大三'
});
const changeObj = () => {
    obj.value.name = '李大四';
    triggerRef(obj); // 此时数据具有响应式
}

2、自定义ref ---- customRef

import {customRef} from 'vue';
function MyRef<T>(value: T) {
    return customRef((trank, trigger) => {
        return {
            get() {
                trank();
                return value;
            },
            set(newValue) {
                value = newValue;
                trigger();
            }
        };
    })
}
let message = MyRef<string>('张三');
const onChange = () => {
    message.value = '李四';
}

3、reactive

import {reactive} from 'vue';
let message = reactive<number[]>([]) // [] {}
setTimeout(() => {
    let arr = [1, 2, 3, 4];
    message = arr; // 这么赋值就失去了message的响应式功能
    message.push(...arr); // 这么赋值还具有响应式
}, 2000)

4、shallowReactive

只是对象的第一层具有响应式

import {shallowReactive} from 'vue';
let message = shallowReactive({
    test: '我是小满',
    nav: {
        bar: {
            name: '我是大满贯'
        }
    }
});
const change1 = () => {
    message.test = '我被修改了'; // 视图会跟着改变
};
const change2 = () => {
    message.nav.bar.name = '我被修改了呢'; // 视图不会跟着改变
}

5、toRef, toRefs

<div>{{state}}</div>

import {reactive, toRef} from 'vue';
const obj = {
    foo: 1,
    bar: 1
};
const state = toRef(obj, 'bar');
const change = () => {
    state.value++;  // 视图不会跟着改变
    console.log('原始对象obj', obj);
    console.log('-->引用对象', state);
}

const obj2 = reactive({
    foo: 1,
    bar: 1
});
const state = toRef(obj2, 'bar');
const change = () => {
    state.value++; // 视图会跟着改变
}

原始对象是响应式的,toRef之后依然还是响应式的;原始对象不是响应式的,则toRef之后依然不是响应式的

import {reactive, toRefs} from 'vue';
const obj = reactive({
    foo: 1,
    bar: 1
});
const {foo, bar} = obj; // 此时结构出来的值不是响应式的

const {foo, bar} = toRefs(obj); // 此时结构出来的值是有响应式的

6、toRaw

将响应式对象转化成原始对象

import {reactive, toRaw} from 'vue';
const obj = reactive({
    foo: 1,
    bar: 1
});
const raw = toRaw(obj); // 将响应式对象编变成原始对象