在Vue3中创建响应数据有两种方式一种是ref,另一种就是reactive
reactive
首先在该组件引入
import {
ref, reactive } from "vue";
<template>
<div>
<p>姓名:{
{
obj.name}}</p>
<p>年龄:{
{
obj.age}}</p>
<p v-for="(item,index) in obj.habby" :key="index">爱好{
{
index+1}}:{
{
item}}</p>
</div>
</template>
<script>
import {
reactive } from "vue";
export default {
name: "App",
setup() {
let obj = reactive({
name: "zjq",
age: 18,
habby: ["跳舞", "唱歌", "游泳"]
});
return {
obj}
}
};
</script>
使用reactive创建的数据,也是需要return 出去,才能在视图层使用。
改变年龄:
<template>
<div>
<p>姓名:{
{
obj.name}}</p>
<p>年龄:{
{
obj.age}}</p> <button @click="ageFun">年龄加一</button>
<p v-for="(item,index) in obj.habby" :key="index">爱好{
{
index+1}}:{
{
item}}</p>
</div>
</template>
<script>
import {
reactive } from "vue";
export default {
name: "App",
setup() {
let obj = reactive({
name: "zjq",
age: 18,
habby: ["跳舞", "唱歌", "游泳"]
});
function ageFun() {
obj.age++
}
return {
obj,ageFun}
}
};
</script>
改变年龄成功,和ref相比较的话,我们这里少了一层value,
ref和reactive两个,ref的底层是reactive可以理解为
ref(0)==>>reactive({value:0})
setup() {
let num = ref(0)
let num2 = reactive({
value:0})
console.log(num.value ===num2.value) //true
}
在页面上使用的时候会判断该响应数据是否为ref创建的数据,是的话自动.value取数据;
判断依据为
__v_isRef 等于true说明是ref创建的响应变量。
代码整理:
<template>
<div>
<p>姓名:{
{
obj.name}}</p>
<p>年龄:{
{
obj.age}}</p>
<button @click="ageFun">年龄加一</button>
<p v-for="(item,index) in obj.habby" :key="index">爱好{
{
index+1}}:{
{
item}}</p>
</div>
</template>
<script>
import {
ref, reactive } from "vue";
export default {
name: "App",
setup() {
let num = ref(0);
let num2 = reactive({
value:0});
console.log(num.value == num2.value);
let {
obj, ageFun } = reactiveF();
return {
obj, ageFun };
}
};
function reactiveF() {
let obj = reactive({
name: "zjq",
age: 18,
habby: ["跳舞", "唱歌", "游泳"]
});
function ageFun() {
obj.age++;
}
return {
obj, ageFun };
}
</script>