赞
踩
作用:定义对象类型的响应式数据。
语法:const 代理对象 = reactive(源对象 or 数组)返回一个proxy的实例对象。
内部基于es6的Proxy实现,通过代理对象操作源对象的数据。
看一段代码和打印结果
<template> <p>个人信息</p> <p>姓名:{{ name }}</p> <p>年龄:{{ age }}</p> <p>妈妈:{{ state.mother }}</p> <p>爸爸:{{ state.father }}</p> </template> <script lang="ts"> import { defineComponent, ref, reactive } from "vue"; export default defineComponent({ name: "Home", components: {}, setup() { let name = ref("张三"); let age = ref("18"); let state = reactive({ mother: "李四", father: "王五", }); console.log("state", state); return { name, age, state, }; }, }); </script>
我们发现打印的并不是一个普通的Object对象,而是一个Proxy对象,这与使用ref处理普通的Object对象类型时,使用的对象类型时一致的(也就是为啥ref也能处理对象类型数据的原因,ref处理对象类型时用的是reactive),reactive比ref更方便的是,不需要通过.value拿到值。
<template> <p>个人信息</p> <p>姓名:{{ name }}</p> <p>年龄:{{ age }}</p> <p>妈妈:{{ state.mother }}</p> <p>爸爸:{{ state.father }}</p> <button @click="edit">修改数据</button> </template> <script lang="ts"> import { defineComponent, ref, reactive } from "vue"; export default defineComponent({ name: "Home", components: {}, setup() { let name = ref("张三"); let age = ref("18"); let state = reactive({ mother: "李四", father: "王五", }); // console.log("state", state); const edit = () => { state.mother = '赵六', state.father = '陈七' }; return { name, age, state, edit }; }, }); </script>
再试一下react是否能够处理数组类型的数据和修改
<template> <p>个人信息</p> <p>姓名:{{ name }}</p> <p>年龄:{{ age }}</p> <p>妈妈:{{ state.mother }}</p> <p>爸爸:{{ state.father }}</p> <p>爱好:{{ hobby }}</p> <button @click="edit">修改数据</button> </template> <script lang="ts"> import { defineComponent, ref, reactive } from "vue"; export default defineComponent({ name: "Home", components: {}, setup() { let name = ref("张三"); let age = ref("18"); let state = reactive({ mother: "李四", father: "王五", }); let hobby = reactive(["足球", "篮球", "羽毛球"]); // console.log("state", state); const edit = () => { hobby[0] = "学习"; }; return { name, age, state, edit, hobby, }; }, }); </script>
说明reactive也能处理数组类型的数据,在日常工作中可能觉得写ref麻烦,也可以这样用reactive
<template> <p>个人信息</p> <p>姓名:{{ person.name }}</p> <p>年龄:{{ person.age }}</p> <p>妈妈:{{ person.family.mother }}</p> <p>爸爸:{{ person.family.father }}</p> <p>爱好:{{ person.hobby }}</p> </template> <script lang="ts"> import { defineComponent, ref, reactive } from "vue"; export default defineComponent({ name: "Home", components: {}, setup() { const person = reactive({ name: "张三", age: 18, family: { mother: "李四", father: "王五", }, hobby: ["足球", "篮球", "羽毛球"] }); return { person }; }, }); </script>
数据也是正常的,这种相对于ref处理基本数据类型,更加语义化。
1、 从定义数据方面:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。