ref
接受一个内部值并返回一个响应式且可变的 ref 对象。ref 对象仅有一个 .value property,指向该内部值。注意被ref包装之后需要.value 来进行赋值
<template>
{{ value11 }}
<button @click="count()">count++</button>
</template>
<script>
import {
ref,
} from "vue";
export default {
setup() {
const value11 = ref(0);
function count() {
value11.value ++;
console.log(value11);
}
return {
count,
value11,
};
},
};
</script>
shallowRef
创建一个跟踪自身 .value 变化的 ref,但不会使其值也变成响应式的
triggerRef
强制更新页面DOM
customRef
customRef 是个工厂函数要求我们返回一个对象 并且实现 get 和 set
可以实现过滤,可以当成计算属性来实现防抖,filters等功能
<template>
ref:{{ valueRef }}
<button @click="changeRef()">改变ref</button>
shallowRef:{{ valueShallowRef }}
<button @click="changeShallowRef()">改变ShallowRef</button>
<button @click="changeShallowRef2()">改变ShallowRef2</button>
<button @click="changeTriggerRef()">改变TriggerRef</button>
myCustomValue:{{ myCustomValue }}
<button @click="changeCustomRef()">改变customRef</button>
</template>
<script>
import { ref, shallowReactive, shallowRef, triggerRef ,customRef} from "vue";
export default {
setup() {
//改变ref
const valueRef = ref(0);
function changeRef() {
valueRef.value++;
}
//改变ShallowRef
const valueShallowRef = shallowRef({
name: "犬夜叉",
});
function changeShallowRef() {
valueShallowRef.value.name = "杀生丸";
console.log(valueShallowRef.value.name);
}
function changeShallowRef2() {
valueShallowRef.value = { name: "杀生丸" };
console.log(valueShallowRef.value.name);
}
function changeTriggerRef() {
valueShallowRef.value.name = "杀生丸";
console.log(valueShallowRef.value.name);
triggerRef(valueShallowRef);
}
function myCustomRef(value) {
return customRef((track, trigger) => {
return {
get() {
//追踪
track();
return value+"爱你破烂的衣裳";
},
set(newValue) {
value = newValue;
//触发更新
trigger();
},
};
});
}
const myCustomValue = myCustomRef("奈落");
function changeCustomRef() {
myCustomValue.value = "米勒法师";
console.log(myCustomValue.value);
}
return {
valueRef,
changeRef,
valueShallowRef,
changeShallowRef,
changeShallowRef2,
changeTriggerRef,
myCustomValue,
changeCustomRef,
};
},
};
</script>