1、reactive shallowreactive
reactive 声明对象为响应式数据的函数,监听对象所有层次的属性 shallowreactive 相比与reative,只监听对象的根属性
const mydata = reactive({
name: '张三',
age: 18,
hobby: ['抽烟', '喝酒']
});
const mydata = shallowReactive({
name: '张三',
age: 18,
hobby: ['抽烟', '喝酒']
});
function change() {
mydata.hobby.push('烫头')
}
2、ref
ref 基础数据为响应式数据
const mydata = ref(0);
function change() {
mydata.value ++;
}
3、readonly shallowReadonly
readonly 声明只读数据的函数,对象中所有层次的属性都是只读 shallowReadonly 相对于shallowReadonly,对象中只有根属性是只读,其他属性允许修改
const mydata = readonly({
name: '张三',
age: 18,
hobby: ['抽烟', '喝酒']
});
const mydata = shallowReadonly({
name: '张三',
age: 18,
hobby: ['抽烟', '喝酒']
});
function change() {
mydata.hobby.push('烫头')
}
4、computed
响应式数据变化了,computed 函数只会第1次调用,其他情况使用缓存
const mydata = ref('这是一段标题');
const getLen = computed(() => {
console.log("计算长度")
return mydata.value.length;
});
function change() {
mydata.value = mydata.value + "!";
}
5、watch 侦听器
监听响应式数据
const count = ref(0);
function change() {
count.value++;
}
// 监听基本数据的响应式数据
watch(count, (newValue, oldValue) => {
console.log(newValue, oldValue);
})
const mydata = reactive({
name: '张三',
age: 18,
hobby: ['抽烟', '喝酒']
})
function change() {
mydata.age ++;
}
// 监听响应式数据对象内部属性
watch(() => mydata.age, (newValue, oldValue) => {
console.log(newValue, oldValue);
})
6、watchEffect 侦听多个响应式数据
const count = ref(0);
const mydata = reactive({
name: '张三',
age: 18,
hobby: ['抽烟', '喝酒']
});
function change() {
count.value ++;
}
function change2() {
mydata.age ++;
}
watchEffect(() => {
console.log('count的值:' + count.value + ', age的值:' + mydata.age);
});