0
点赞
收藏
分享

微信扫一扫

VUE框架Vue3下使用ref函数包裹的对象实现响应式处理------VUE框架

<template>
    <h1>{{ userRefImpl.name }}</h1>
    <h1>{{ userRefImpl.age }}</h1>
    <h1>{{ count }}</h1>
    <h1>{{ userRefImpl.addr.city }}</h1>
    <h1>{{ userRefImpl.addr.street }}</h1>
    <button @click="modifyUser">修改</button>
</template>
 
<script>
import {ref} from 'vue';
export default {
    name : "App",
    // setup(){
    //     // data
    //     // 如果这里是一个对象,默认也是没有响应式处理的
    //     let user = {
    //         name : "Jack",
    //         age : 20
    //     };
    //     // methods
    //     function modifyUser(){
    //         user.name = "Rose";
    //         user.age = 30;
    //     }
    //     // 返回对象
    //     return {user,modifyUser};
    // }
    setup(){
        // 我们这里的是一个对象
        // 这里的ref代理对象因为操作的是对象,底层即会提供get和set用于修改该对象
        // 这里的get和set方法是通过Object.defineProperty实现的
        // 又会提供一个proxy代理对象作为value
        // 让我们得以通过Proxy的机制实现响应式处理数据
        let userRefImpl = ref({
            name : "Jack",
            age : 20,
            // ref包裹的对象的子对象都有响应式处理,是通过递归方式实现的
            // Proxy实现的响应式,对象中的对象,都有响应式处理,底层是递归处理了
            addr : {
                city : "北京",
                street : "大兴区凉水河街道"
            }
        });
        let count = ref(100);
        console.log(count);
        console.log(userRefImpl);
        function modifyUser(){
            // 在这里我们会操作到这个对象的代理对象Proxy
            // 这样修改就可以实现响应式操作了
            userRefImpl.value.name = "Rose";
            userRefImpl.value.age = 30;
            count.value =  200;
            userRefImpl.value.addr.city = "南京";
            userRefImpl.value.addr.street = "雨花石巷";
        }
        return {userRefImpl,count,modifyUser};
    }
}
</script>
 
<style>
 
</style>

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <link rel="icon" href="/favicon.ico">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vite App</title>
  </head>
  <body>
    <!-- 和webpack创建的工程区别,index.html放在了pubic的外面 -->
    <!-- Vite以index.html作为入口,不再使用main.js作为入口了 -->
    <!-- 对于vite构建工具来说,配置文件时vite.config.js -->
    <!-- 这个vite.config.js类似于webpack打包的vue.config.js -->
    <div id="app"></div>
    <script type="module" src="/src/main.js"></script>
  </body>
</html>

举报

相关推荐

0 条评论