通过一个例子讲解Vue组合式API
2024-04-09 23:50:11  阅读数 1345

一、Composition API概述

当我们编写Vue组件时候,组件中可能包含一系列的功能,例如一个代码仓库管理的应用,用户的仓库列表可以看做是一个组件,这个组件还包含筛选、搜索的功能。

所谓的功能我们可以理解为MVC中的Model和Controller。从视图角度,组件是最基本的代码复用单元,但是从逻辑上,功能模块是最基本的代码复用单元。

每个组件中可能包含多个功能(也称为关注点),而多个功能的代码会分散在Vue组件的各个部分:data/props/watch/computed/dom event callback/lifescycle。

这会带来两个问题:

  1. 可读性和可维护性差,比如我们想要阅读某个功能的逻辑,需要翻遍整个组件,到处查看相应的逻辑;当需要改动某个功能时候,需要在很多地方进行改动。
  2. Vue未提供功能模块级别的代码复用支持,只提供组件级别的复用的话,在大型项目中是不够的。

为了解决上面两个问题,Vue需要提供功能模块级别的代码组织方式,即需要将同一个功能模块的代码写在同一片区域,而不是分散到组件的各个API中,另外还需要支持功能模块的封装,以便我们可以提取功能模块的代码进行复用。

如何实现上述两个能力呢?我们看看一个功能模块都包含哪些内容。

  1. 数据
  2. 数据的计算
  3. 数据的更新
  4. 数据监听

其中数据部分的代码写在Vue组件中的data、props中

数据计算部分的代码写在Vue组件中的computed和处理数据的方法中

数据更新部分代码写在生命周期钩子方法和交互事件中

数据监听代码写在watch中

因此我们希望Vue能提供一个API,让我们把一个功能模块(即关注点)的这些代码(包括data/props/computed/watch/dom event callback/lifecycle)都写在一起。并且能将其提取。

组合式API就提供了这样的能力。

总之,组合式API是在Vue3中新增加的API,它有两点优势:

  1. 让功能模块代码(关注点)聚合在一起,使可读性和可维护性更高。
  2. 提供了一种功能模块级别的复用代码的方式。

二、Composition API使用

前端面试刷题网站灵题库,收集大厂面试真题,相关知识点详细解析。

开发者如何使用组合式API呢?简单地说,需要在Vue组件里实现setup方法,并在方法中返回一些方法和属性,返回的所有内容都将暴露给组件的其余部分 (计算属性、方法、生命周期钩子等等) 以及组件的模板。

首先看一个简单的例子,下面是一个单文件组件

<template>
    <div id="app">
        <span class="counter">
            {{counter}}
            <button @click="increase">+1</button>
        </span>

        <div class="msg-panel">
            <span v-if="showMsg">
                hello, world
            </span>
            <button @click="toggleShowCondition">{{showWhenOdd ? '奇数展示' : '偶数展示'}}</button>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            counter: 0,
            showWhenOdd: true
        };
    },
    computed: {
        showMsg() {
            return this.counter % 2 === 0
                ? this.showWhenOdd
                : !this.showWhenOdd;
        }
    },
    mounted() {
        this.counter = Math.floor(Math.random() * 9) + 1;
    },
    methods: {
        increase() {
            this.counter++;
        },
        toggleShowCondition() {
            this.showWhenOdd = !this.showWhenOdd;
        }
    }

};

</script>

<style scoped>
#app {
    text-align: center;
    margin-top: 60px;
}

.counter {
    width: 100px;
    height: 100px;
    border: 1px solid;
    padding: 10px;
}

.msg-panel {
    width: 100px;
    height: 100px;
    margin: 50px auto;
    border: 1px solid;
    padding: 10px;
}
</style>

效果如下:

image.png

这个组件有两个功能

  1. 展示一个计数器,计数器初始化计数是1-10之间的一个随机数,每次点击"+1"按钮会让计数加1,计数实时展示在界面上
  2. 信息展示,仅当计数为偶数时候,才会展示"hello, world"信息。也可以通过点击"奇数展示"按钮来控制 仅当计数为奇数时候展示信息。

理解了上面的功能的实现之后我们再来看下使用组合式API如何实现相同的功能。

<template>
    <div id="app">
        <span class="counter">
            {{counter}}
            <button @click="increase">+1</button>
        </span>

        <div class="msg-panel">
            <span v-if="showMsg">
                hello, world
            </span>
            <button @click="toggleShowCondition">{{showWhenOdd ? '奇数展示' : '偶数展示'}}</button>
        </div>
    </div>
</template>

<script>
import {ref, onMounted, computed} from 'vue';

export default {
    setup() {
        // counter逻辑
        const counter = ref(0);
        const increase = () => {
            counter.value++;
        };
        onMounted(() => {
            counter.value = Math.floor(Math.random() * 9) + 1;
        });

        // 提示信息逻辑
        const showWhenOdd = ref(true);
        const showMsg = computed(() => {
            return counter.value % 2 === 0
                ? showWhenOdd.value
                : !showWhenOdd.value;
        });
        const toggleShowCondition = () => {
            showWhenOdd.value = !showWhenOdd.value;
        };

        return {
            counter,
            increase,
            showWhenOdd,
            showMsg,
            toggleShowCondition
        };
    }
};

</script>

<style scoped>
#app {
    text-align: center;
    margin-top: 60px;
}

.counter {
    width: 100px;
    height: 100px;
    border: 1px solid;
    padding: 10px;
}

.msg-panel {
    width: 100px;
    height: 100px;
    margin: 50px auto;
    border: 1px solid;
    padding: 10px;
}
</style>

上面使用了组合式API的示例实现了相同的功能,注意:

  1. 之前的各种Vue组件的属性 data/methods/computed/mounted等被setup方法代替,setup方法返回的值里面包括模板需要用到的数据和方法。
  2. 之前组件的data里面的数据(counter、showWhenOdd)用ref(<初始值>)代替,数据使用时候,需要通过.value取值。
  3. 之前写在methods中的方法都在setup方法里面实现并返回。
  4. 之前写在computed中的计算属性通过vue中的computed实现,computed接受一个函数,函数返回计算结果。
  5. 之前生命周期钩子mounted被setup中通过onMounted包裹的函数来代替。

对比两段代码我们可以看出,使用setup API的实现明显可以将两段功能逻辑(counter展示提示信息)各自聚合在一起

image.png

这样就实现了我们之前提到的“让功能模块代码(关注点)聚合在一起,使可读性和可维护性更高”的效果,如果我们还希望实现“提供了一种功能模块级别的复用代码的方式”,我们可以这样组织代码:

<template>
    <div id="app">
        <span class="counter">
            {{counter}}
            <button @click="increase">+1</button>
        </span>

        <div class="msg-panel">
            <span v-if="showMsg">
                hello, world
            </span>
            <button @click="toggleShowCondition">{{showWhenOdd ? '奇数展示' : '偶数展示'}}</button>
        </div>
    </div>
</template>

<script>
import {ref, onMounted, computed} from 'vue';

const useCounter = () => {
    // counter逻辑
    const counter = ref(0);
    const increase = () => {
        counter.value++;
    };
    onMounted(() => {
        counter.value = Math.floor(Math.random() * 9) + 1;
    });

    return {
        counter,
        increase
    };
};

const useMsg = counter => {
    const showWhenOdd = ref(true);
    const showMsg = computed(() => {
        return counter.value % 2 === 0
            ? showWhenOdd.value
            : !showWhenOdd.value;
    });
    const toggleShowCondition = () => {
        showWhenOdd.value = !showWhenOdd.value;
    };

    return {
        showWhenOdd,
        showMsg,
        toggleShowCondition
    };
};

export default {
    setup() {
        const {counter, increase} = useCounter();
        const {showWhenOdd, showMsg, toggleShowCondition} = useMsg(counter);

        return {
            counter,
            increase,
            showWhenOdd,
            showMsg,
            toggleShowCondition
        };
    }
};

</script>

<style scoped>
#app {
    text-align: center;
    margin-top: 60px;
}

.counter {
    width: 100px;
    height: 100px;
    border: 1px solid;
    padding: 10px;
}

.msg-panel {
    width: 100px;
    height: 100px;
    margin: 50px auto;
    border: 1px solid;
    padding: 10px;
}
</style>

通过上面示例可以看到,我们将不同的功能模块封装在函数中,并将关键数据和方法返回,然后在Vue组件的setup方法中引用并返回,就可以在模板中使用了。

除了上述的几个关键API:setup/ref/computed/onMounted,还有toRef用于解构props中的属性,watch用于监听数据,代替Vue组件中的watch属性。可以在官方文档查看用法。