分类目录: html5
vue3中声明响应式数据ref和reactive
Post date:
Author: cyy
标签: vue3
Number of comments: no comments
vue2的双向数据绑定是在data中,不论基本数据类型还是引用数据类型。
data() {
return {
colNum: 10,
rowNum: 10,
formData: {
rackId: "",
mapDetail: [],
},
};
}
vue3中的双向数据绑定依赖了ref和reactive
ref是绑定基本数据类型的
reactive一般是绑定引用数据类型的。
ref可绑定:
- String
- Number
- BigInt
- Boolean
- Symbol
- Null
- Undefined
- Array
注:ref绑定的数据在setup里要用.value,在模板里则不用,模板直接识别
reactive可绑定:
- Object
- Array
- Function
注:toRefs()函数可以将reactive()创建出来的响应式对象,转换为普通对象,在模板中就可以直接使用属性,不用obj.name
例:
<template>
<section>
<div>num:{{ num }}</div>
<div>arr2:{{ arr2 }}</div>
<div>type:{{ type }}</div>
<div>name:{{ name }}</div>
<div>age:{{ age }}</div>
<div>arr:{{ arr }}</div>
<button @click="addArr2">add arr2</button>
<button @click="addNum">add num</button>
<button @click="addArr">add arr</button>
</section>
</template>
<script>
import { reactive, ref, toRefs } from "vue";
export default {
setup() {
const num = ref(1);
const arr2 = ref([2, 2, 2, 2]);
const type = ref("test");
const obj = reactive({
name: "猫猫草",
age: 50,
});
const { name, age } = toRefs(obj);
const arr = reactive([0, 1, 2, 3, 4]);
const addNum = () => {
num.value++;
};
const addArr = () => {
arr[0]++;
};
const addArr2 = () => {
arr2.value[0]++;
};
return {
num,
arr2,
type,
...{ name, age },
arr,
addNum,
addArr,
addArr2,
};
},
};
</script>
<style lang="scss">
</style>
目前刚接触,理解得还不是很透彻~有啥不对请谅解!