在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>
<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和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
}
代码整理:
<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>