Vue3 | Composition API 包括setup、ref等新特性详解 与 实战

本文详细介绍了Vue3的Composition API,包括setup函数、ref的使用,以及如何处理非响应引用。文章通过实战案例展示了如何利用Composition API提升代码可维护性和开发效率,讲解了setup中的计算属性、watch监听、生命周期钩子以及provide/inject的使用。
摘要由CSDN通过智能技术生成

完整原文地址见简书

 

更多完整Vue笔记目录敬请见《前端 Web 笔记 汇总目录(Updating)》

本文内容提要

  • Composition API 的作用
  • setup函数
  • 例程,打印查看setup内容
  • 非响应引用的案例
  • ref()概念、原理 与 实战
  • reactive()概念、原理 与 实战
  • 使用readonly限制对象的访问权限
  • 使用toRefs()reactive对象进一步封装
  • 多个属性进行解构
  • 多个属性 配合toRefs() 进行解构
  • toRefs()无法处理 undefined的键值
  • 使用toRef()应对上述问题
  • 关于setup函数的三个参数【attrs、slots、emit】
  • 回顾 没有 CompositionAPI时,emit的用法
  • 使用setup的 context.emit 替代 this.$emit
  • 使用Composition API开发 todoList
  • 完善toDoList案例
  • 优化上例的逻辑结构!
  • setup的 computed 计算属性
  • 当然以上是computed 的默认用法,实际上它可以接收一个对象
  • 将上例的处理值换成 Object类型,再例
  • setup 中的 watch 监听
  • setup 中的 watch 监听:监听Object类型
  • setup 中的 watch 监听:监听Object类型的 多个属性
  • setup 中的 watchEffect监听 以及 与 watch 的异同比较
  • 两者都可以用以下的方式,在一个设定的时延之后,停止监听
  • 为 watch 配置 immediate属性,可使具备同watchEffect的 即时性
  • setup 中的 生命周期
  • setup中的provide、inject用法
  • 配合上ref实现 响应特性 以及 readonly实现 单向数据流
  • setup结合ref指令

Composition API 的作用

使得相同的、相关的功能代码 可以比较 完整地聚合起来,
提高可维护性、可读性,提高开发效率;
规避 同一个功能的代码,
却散落在 组件定义中的data、methods、computed、directives、template、mixin等各处 的问题;

setup函数

--- Composition API 所有代码编写之前,
都要 建立在setup函数 之上;
--- 在created 组件实例 被完全初始化之前 回调;
(所以注意在setup函数中,
使用与this相关的调用是没有用的)
--- setup函数中的内容,
可以在 该组件的 模板template 中直接使用;
(如下例程)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>

    const app = Vue.createApp({

        template: `
            <div @click="handleClick">{
  {name}}</div>    
        `,

        setup(props, context) {
            return {
                name: 'zhao',
                handleClick: () => {
                    alert(666);
                }
            }
        }
    });

    const vm = app.mount('#heheApp');
</script>
</html>

例程,打印查看setup内容

<script>

    const app = Vue.createApp({

        template: `
            <div @click="handleClick">{
  {name}}</div>    
        `,
        methods: {
            test() {
                console.log(this.$options);
            }
        },
        mounted() {
            this.test();
        },
        setup(props, context) {
            return {
                name: 'zhao',
                handleClick: () => {
                    alert(666);
                }
            }
        }
    });

    const vm = app.mount('#heheApp');
</script>

由于调用时序的关系,setup中 无法调用this等相关 如变量、methods中 等 其他内容,但是其他内容 却可以调用 setup函数!!【setup生时众为生,众生时setup已生】

<script>

    const app = Vue.createApp({

        template: `
            <div @click="handleClick">{
  {name}}</div>    
        `,
        methods: {
            test() {
                console.log(this.$options.setup());
            }
        },
        mounted() {
            this.test();
        },
        setup(props, context) {
            return {
                name: 'zhao',
                handleClick: () => {
                    alert(666);
                }
            }
        }
    });

    const vm = app.mount('#heheApp');
</script>

非响应引用的案例

如下,这样没有使用ref/reactive的写法,是不会有响应的:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>

    const app = Vue.createApp({

        template: `
            <div>{
  {name}}</div>    
        `,
        setup(props, context) {
            let name = 'guan';
            setTimeout(() => {
                name = 'zhao';
            }, 2000);
            return { name }
        }
    });

    const vm = app.mount('#heheApp');
</script>
</html>

如下,运行之后,两秒延时之后,DOM文本展示并不会自动改成zhao,而是一直展示初始化的guan

ref()概念、原理 与 实战

使用ref可以 用于处理 基础类型的数据,赋能响应式
原理:通过 proxy 将 数据 封装成
类似 proxy({value: '【变量值】'})这样的一个响应式引用
数据变化时,就会 触发template等相关UI的更新
【赋予 非data中定义的变量 以响应式的能力 ——
原先,我们是借助Vue的data函数,完成响应式变量的定义的;
有了ref之后,我们可以不借助data中的定义,
而直接在普通的函数中对js变量proxy封装,
就可以对 普通的js引用 赋能响应式了】;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>

    const app = Vue.createApp({

        template: `
            <div>{
  {name}}</div>    
        `,
        setup(props, context) {
            const { ref } = Vue;
            let name = ref('guan');
            setTimeout(() => {
                name.value = 'zhao';
            }, 2000);
            return { name }
        }
    });

    const vm = app.mount('#heheApp');
</script>
</html>

运行效果:


两秒后自动变化:

reactive()概念、原理 与 实战

使用reactive()用于处理 非基础类型的数据(如Object、Array),赋能响应式
原理类似ref(),只是处理的数据格式不同而已;

如下,普通的Object类型是没有响应式的效果的:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>

    const app = Vue.createApp({

        template: `
            <div>{
  {nameObj.name}}</div>    
        `,
        setup(props, context) {
            // const { ref } = Vue;
            const nameObj = { name: 'guan'};
            setTimeout(() => {
                nameObj.name = 'zhao';
            }, 2000);
            return { nameObj }
        }
    });

    const vm = app.mount('#heheApp');
</script>
</html>

使用reactive()处理Object类型后,具备响应式的能力:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>

    const app = Vue.createApp({

        template: `
            <div>{
  {nameObj.name}}</div>    
        `,
        setup(props, context) {
            const { reactive } = Vue;
            const nameObj = reactive({ name: 'guan'});
            setTimeout(() => {
                nameObj.name = 'zhao';
            }, 2000);
            return { nameObj }
        }
    });

    const vm = app.mount('#heheApp');
</script>
</html>

运行效果:


两秒后自动变化:

使用reactive()处理Array类型数据

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello World! heheheheheheda</title>
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="heheApp"></div>
</body>
<script>

    const app = Vue.createApp({

        template: `
            <div>{
  {nameObj[0]}}</div>    
        `,
      
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凌川江雪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值