The difference between Vue3 and Vue2 in the eyes of a Java ape

With the recording of the TienChin project video, Song Ge finally has to calm down and take a look at the various new features in Vue3, and then share it with his friends. In fact, Vue3 still brings a lot of new things. , today we will not roll Java, let's roll the front end.

The following content is a Java ape's understanding of Vue3, mainly at the application level. If you have a professional front-end partner, please tap.

1. script writing

Entering the era of Vue3, the most obvious feeling is that in a .vue file, the way the script tag is written has changed greatly. Before in Vue2, we all wrote like this:

<script>
    export default {
        name: "SysHr",
        data() {
            return {
                //
            }
        },
        mounted() {
            //
        },
        methods: {
            deleteHr(hr) {
                //
            },
            doSearch() {
                //
            }
        }
    }
</script>

However, in Vue3, this way of writing has changed, and it becomes the following:

<template>
    <div>
        <div>{{a}}</div>
        <div>{{result}}</div>
        <button @click="btnClick">clickMe</button>
    </div>
</template>
<script>

    import {ref} from 'vue';
    import {onMounted,computed} from 'vue'

    export default {
        name: "MyVue01",
        setup() {
            const a = ref(1);
            const btnClick=()=>{
                a.value++;
            }
            onMounted(() => {
                a.value++;
            });
            const result = computed(()=>{
                return Date.now();
            });
            return {a,btnClick,result}
        }
    }
</script>

Let’s look at the big picture first, and let’s talk about the details later.

The big aspect is that in this export default, there will be only two elements in the future, name and setup. Our previous various method definitions, life cycle functions, computed properties, etc. are all written in setup, and need to be in setup. What is returned in setup, what can be used in the above template.

This way of writing is a bit cumbersome, so there is a simplified way of writing it, like this:

<template>
    <div>
        <div>{{a}}</div>
        <div>{{result}}</div>
        <button @click="btnClick">clickMe</button>
    </div>
</template>

<script setup>

    import {ref} from 'vue';
    import {onMounted, computed} from 'vue'

    const a = ref(1);
    const btnClick = () => {
        a.value++;
    }
    onMounted(() => {
        a.value++;
    });
    const result = computed(() => {
        return Date.now();
    });
</script>

This way of writing is to add setup directly to the script tag, and then define how it is defined in the script tag, and there is no need to return. This scene has a bit of jQuery feel again.

There are several details in the above implementation, let's talk about it in detail.

2. Lifecycle

The first is the way of writing the life cycle function.

In the past, there was a professional term called options API in Vue2, and now there is also a professional term in Vue3 called composition API. In Vue3, these corresponding life cycle functions must be exported from vue first, and then call and pass in a callback function, as we wrote in the previous section.

The following table shows the one-to-one correspondence between options API and composition API:

options API composition API
beforeCreate Not Needed
created Not Needed
mounted onMounted
beforeUpdate onBeforeUpdate
updated onUpdated
beforeUnmount onBeforeUnmount
unmounted onUnmounted
errorCaptured onErrorCaptured
renderTracked onRenderTracked
renderTriggered onRenderTriggered
activated onActivated
deactivated onDeactivated

想用哪个生命周期函数,就从 vue 中导出这个函数,然后传入回一个回调就可以使用了。例如第一小节中松哥给大家举的 onMounted 的用法。

3. 计算属性

除了生命周期函数,计算属性、watch 监听等等,用法也和生命周期函数类似,需要先从 vue 中导出,导出之后,也是传入一个回调函数就可以使用了。上文有例子,我就不再啰嗦了。

像 watch 的监控,写法如下:

<script>

    import {ref} from 'vue';
    import {onMounted,computed,watch} from 'vue'

    export default {
        name: "MyVue01",
        setup() {
            const a = ref(1);
            const btnClick=()=>{
                a.value++;
            }
            onMounted(() => {
                a.value++;
            });
            const result = computed(()=>{
                return Date.now();
            });
            watch(a,(value,oldValue)=>{
                console.log("value", value);
                console.log("oldValue", oldValue);
            })
            return {a,btnClick,result}
        }
    }
</script>

导入 watch 之后,然后直接使用即可。

4. ref 于 reactive

上面的例子中还有一个 ref,这个玩意也需要跟大家介绍下。

在 Vue2 里边,如果我们想要定义响应式数据,一般都是写在 data 函数中的,类似下面这样:

<script>
    export default {
        name: "SysHr",
        data() {
            return {
                keywords: '',
                hrs: [],
                selectedRoles: [],
                allroles: []
            }
        }
    }
</script>

但是在 Vue3 里边,你已经看不到 data 函数了,那怎么定义响应式数据呢?就是通过 ref 或者 reactive 来定义了。

在第一小节中,我们就是通过 ref 定义了一个名为 a 的响应式变量。

这个 a 在 script 中写的时候,有一个 value 属性,不过在 HTML 中引用的时候,是没有 value 的,可千万别写成了 {{a.value}},我们再来回顾下上文的案例:

<template>
    <div>
        <div>{{a}}</div>
        <button @click="btnClick">clickMe</button>
    </div>
</template>

<script>

    import {ref} from 'vue';

    export default {
        name: "MyVue04",
        setup() {
            const a = ref(1);
            const btnClick=()=>{
                a.value++;
            }
            return {a,btnClick}
        }
    }
</script>

现在就是通过这样的方式来定义响应式对象,修改值的时候,需要用 a.value,但是真正的上面的 template 节点中访问的时候是不需要 value 的(注意,函数也得返回后才能在页面中使用)。

和 Vue2 相比,这种写法有一个很大的好处就是在方法中引用的时候不用再写 this 了。

ref 一般用来定义原始数据类型,像 String、Number、BigInt、Boolean、Symbol、Null、Undefined 这些。

如果你想定义对象,那么可以使用 reactive 来定义,如下:

<template>
    <div>
        <div>{{a}}</div>
        <button @click="btnClick">clickMe</button>
        <div>{{book.name}}</div>
        <div>{{book.author}}</div>
    </div>
</template>

<script>

    import {ref, reactive} from 'vue';

    export default {
        name: "MyVue04",
        setup() {
            const a = ref(1);
            const book = reactive({
                name: "三国演义",
                author: "罗贯中"
            });
            const btnClick = () => {
                a.value++;
            }
            return {a, btnClick,book}
        }
    }
</script>

这里定义了 book 对象,book 对象中包含了 name 和 author 两个属性。

有的时候,你可能批量把数据定义好了,但是在访问的时候却希望直接访问,那么我们可以使用数据展开,像下面这样:

<template>
    <div>
        <div>{{a}}</div>
        <button @click="btnClick">clickMe</button>
        <div>{{name}}</div>
        <div>{{author}}</div>
    </div>
</template>

<script>

    import {ref, reactive} from 'vue';

    export default {
        name: "MyVue04",
        setup() {
            const a = ref(1);
            const book = reactive({
                name: "三国演义",
                author: "罗贯中"
            });
            const btnClick = () => {
                a.value++;
            }
            return {a, btnClick,...book}
        }
    }
</script>

这样,在上面访问的时候,就可以直接访问 name 和 author 两个属性了,就不用添加 book 前缀了。

不过!!!

这种写法其实有一个小坑。

比如我再添加一个按钮,如下:

<template>
    <div>
        <div>{{a}}</div>
        <button @click="btnClick">clickMe</button>
        <div>{{name}}</div>
        <div>{{author}}</div>
        <button @click="updateBook">更新图书信息</button>
    </div>
</template>

<script>

    import {ref, reactive} from 'vue';

    export default {
        name: "MyVue04",
        setup() {
            const a = ref(1);
            const book = reactive({
                name: "三国演义",
                author: "罗贯中"
            });
            const btnClick = () => {
                a.value++;
            }
            const updateBook=()=>{
                book.name = '123';
            }
            return {a, btnClick,...book,updateBook}
        }
    }
</script>

这个时候点击更新按钮,你会发现没反应!因为用了数据展开之后,响应式就失效了。所以,对于这种展开的数据,应该再用 toRefs 来处理下,如下:

<template>
    <div>
        <div>{{a}}</div>
        <button @click="btnClick">clickMe</button>
        <div>{{name}}</div>
        <div>{{author}}</div>
        <button @click="updateBook">更新图书信息</button>
    </div>
</template>

<script>

    import {ref, reactive, toRefs} from 'vue';

    export default {
        name: "MyVue04",
        setup() {
            const a = ref(1);
            const book = reactive({
                name: "三国演义",
                author: "罗贯中"
            });
            const btnClick = () => {
                a.value++;
            }
            const updateBook = () => {
                book.name = '123';
            }
            return {a, btnClick, ...toRefs(book),updateBook}
        }
    }
</script>

当然,如果你将 setup 直接写在了 script 标签中,那么可以直接按照如下方式来展开数据:

<template>
    <div>
        <div>{{a}}</div>
        <button @click="btnClick">clickMe</button>
        <div>{{name}}</div>
        <div>{{author}}</div>
        <button @click="updateBook">更新图书信息</button>
    </div>
</template>

<script setup>

    import {ref, reactive, toRefs} from 'vue';

    const a = ref(1);
    const book = reactive({
        name: "三国演义",
        author: "罗贯中"
    });
    const btnClick = () => {
        a.value++;
    }
    const updateBook = () => {
        book.name = '123';
    }
    const {name, author} = toRefs(book);
</script>

5. 小结

好啦,今天就和小伙伴们分享了 Vue3 中几个新鲜的玩法~作为我们 TienChin 项目的基础(Vue 基本用法在 vhr 中都已经讲过了,所以这里就不再赘述了),当然,Vue3 和 Vue2 还有其他一些差异,这些我们都将在 TienChin 项目视频中和小伙伴们再仔细分享。

Guess you like

Origin juejin.im/post/7121596766893867016