← 返回首页
Vue3基础教程(十八)
发表时间:2021-08-09 01:08:40
reactive

理解reactive

reactive的作用是定义对象类型的响应式数据。

ref与reactive的对比 ref与reactive方法的区别是什么?一个是把值类型添加一层包装,使其变成响应式的引用类型的值。另一个则是引用类型的值变成响应式的值。所以两者的区别只是在于是否需要添加一层引用包装?其目的都是对数据添加响应式效果。

实例:

点击按钮更新一个学生对象的属性。

<template>
    <!--与vue2模板的区别:不需要定义一个根标签-->
    <h1>第一个Vue3案例</h1>
    <hr>
    <table class="mytab">
        <tr>
            <th>学号</th>
            <th>姓名</th>
            <th>年龄</th>
        </tr>
        <tr>
            <td>{{stu.sid}}</td>
            <td>{{stu.sname}}</td>
            <td>{{stu.age}}</td>
        </tr>
        <tr>
            <td colspan="3"><button @click="changeStudentInfo">更改学生属性</button></td>
        </tr>
    </table>
</template>

<script lang="ts">
    import {defineComponent, ref, reactive} from 'vue';

    export default defineComponent({
        name: 'App',
        setup() {
            //返回代理对象
            const stu = reactive({
                sid: 'S001',
                sname: 'zhangsan',
                age: 20
            });

            function changeStudentInfo(){
                stu.sid = 'S002';
                stu.sname = '李四';
                stu.age = 18;
                console.log(stu);
            }
           return {
                stu,
                changeStudentInfo
            }
        }
    });
</script>

我们发现控制输出stu的内容是一个代理对象。

Proxy {sid: "S002", sname: "李四", age: 18}
[[Handler]]: Object
[[Target]]: Object
[[IsRevoked]]: false