ref和reactive的使用
- ref和reactive的使用场景区别
1、ref可以包装基本类型、数组、对象;reactive只能用来包装引用类型。
2、ref包装的数组和对象可以整体赋值,reactive包装的引用类型不能整体被赋值
3、ref在script中需要'.value'出来;reactive不需要
- 常常这样用
1、基本类型用ref
let n = ref(0);
n.value = 1;
2、数组用ref
let arr = ref([1,2]);
arr.value = [1,2,3];
3、对象用reactive
let obj = reactive({name: 'jim'});
Object.assign(obj,{age: 18}); -> {name:'jim', age:18}
- 使用ref获取dom
<div ref="xx">
API选项中:
this.$refs.xx
setup中:
const xx = ref(),在onMounted中使用
- 从reactive对象中解构出属性作为响应式数据使用
let obj = reactive({
name: 'jim',
age: 18
})
let {name, age} = toRefs(obj) // 此时name和age就是响应式的数据
props
在模板中可以直接使用msg属性,在script中要props.msg
- composition api中的props
<template>
{{name}}
</template>
export default {
props: {
name: {}
},
setup(props) {
console.log(props.name)
}
}
- setup语法糖非TS写法
const props = defineProps({
msg: {
type: String,
default: 'ss'
},
list: {
type: Array,
// 对于引用类型,需要函数形式给默认值
default: () => []
}
})
- setup语法糖TS写法
const props = withDefaults(defineProps<{
msg?: String,
list: Array
}>(),{
msg: 'sss',
// 对于引用类型,需要函数形式给默认值
list: () => []
})
computed
返回值类似一个ref包装的响应式对象,在script中需要.value进行拆箱
- 常规使用
let aa = computed(() => {根据已知响应式数据return一个新的数据})
- 传参使用
回调函数中返回一个函数定义fn,参数作为fn的参数传入
const aa = computed(() => {
return (num) => {
return msg.value + num
}
})
- get和set使用
场景:v-model="aa"
const aa = computed({
get() {
return msg.value + 's'
},
set(n) {
// set函数体中处理相关联的响应数据,可以是data、vuex的状态、props等
// 而并非直接给计算属性设置
// 无需返回任何东西
msg.value += n
}
})