Vue3中ref的妙用

248 阅读1分钟

这是我参与11月更文挑战的第25天,活动详情查看:2021最后一次更文挑战

ref

首先我们来看一个vue2的小案例:

template>
    <div id="app">
        <img alt="Vue logo" src="./assets/logo.png" />
        <h1>{{ count }}</h1>
        <button @click="increase">+1</button>
    </div>
</template>

<script lang="ts">
export default{
    name: "App",
    data() {
        return {
            count: 0,
        };
    },
    methods: {
        increase() {
            this.count++;
        },
    },
};
</script>

<style>
#app {
    font-family: Avenir, Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
}
</style>

这个小案例实现的就是一个点击增加数字的一个小计数器

效果如图:

现在我们用Vue3来修改它:

<template>
    <div id="app">
        <img alt="Vue logo" src="./assets/logo.png" />
        <h1>{{ count }}</h1>
        <h1>{{ double }}</h1>
        <button @click="increase">👍+1</button>
    </div>
</template>

<script lang="ts">
import { ref, computed } from "vue";
export default {
    name: "App",
    setup() {
        const count = ref(0);
        const double = computed(() => {
            return count.value * 2;
        });
        const increase = () => {
            count.value++;
        };
        return {
            count,
            increase,
            double,
        };
    },
};
</script>

<style>
#app {
    font-family: Avenir, Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
}
</style>

效果:

解释代码:

setup()函数:是Vue3中的重中之重,它的本质是Javascript中的function,其内部不能使用this因为 setup() 是在解析其它组件选项之前被调用的,所以setup()内部的 this 的行为与其它选项中的 this 完全不同。

ref:接受一个内部值并返回一个响应式且可变的 ref 对象。这个时候案例中的count就是一个Ref类型:

computed:接受一个 getter 函数,并根据 getter 的返回值返回一个不可变的响应式 ref对象。在上面的案例中dobule是一个ComputeRef类型:

ComputeRef类型:它也是一个类似一个Ref对象的一个数据类型,它也可以直接在我们的模板里面进行使用。

注意:当我们在increas函数中想要更新 count的值的时候不能直接更新,因为它是一个Ref响应式对象的值,我们应该更新的是count.value的值。

总结:

setup():在 setup() 内部,不能使用this

ref:接受一个内部值,返回一个具有高度响应的对象

computed:接受一个函数返回一个ref对象