2

VUE3 之 全局 Mixin 与 自定义属性合并策略 - 这个系列的教程通俗易懂,适合新手 - 追...

 2 years ago
source link: https://www.cnblogs.com/w84422/p/16103894.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

VUE3 之 全局 Mixin 与 自定义属性合并策略 - 这个系列的教程通俗易懂,适合新手

1. 概述

老话说的好:心态决定命运,好心态才能有好的命运。

言归正传,今天我们来聊聊 VUE 中的全局 Mixin 与 自定义属性合并策略。

2. Mixin 的使用

2.1 全局 Mixin

 之前咱们介绍的 Mixin 用法,是局部 Mixin,需要在组件和子组件中使用 mixins:[myMixin] 去引入 Mixin,下面我们介绍 全局 Mixin。

<body>
    <div id="myDiv"></div>
</body>
<script>
    const app = Vue.createApp({
        data(){
            return {
                num : 1
            }
        },

        created() {
            console.info('created');
        },

        methods : {
            myAdd() {
                console.info('myAdd');
            }
        },

        template:`
            <div>
                <button @click="myAdd">增加</button>
                <div>{{num}}</div>
                <sub-com />
            </div>
        `
    });
    app.mixin({
        data(){
            return {
                num : 2,
                count : 1
            }
        },
        created() {
            console.info('myMixin created');
        },
        methods : {
            myAdd() {
                console.info('myMixin myAdd');
            }
        },
    });

    app.component('sub-com', {
        template: `
            <div>{{count}}</div>
        `
    });

    const vm = app.mount("#myDiv");

</script>

 使用 app.mixin 声明的 Mixin 就是全局 Mixin,全局 Mixin 不需要在组件或子组件中使用 mixins:[myMixin] 去引入 Mixin,效果和局部 Mixin 一样。

2.2 自定义属性的使用

    const myMixin = {
        num : 2
    }
    
    const app = Vue.createApp({
        num : 1,

        mixins:[myMixin],

        template:`
            <div>
                <div>{{this.$options.num}}</div>
            </div>
        `
    });

这个例子中的 num 就是自定义属性,渲染时使用 {{this.$options.num}} 得到自定义属性。

自定义属性,不写在 data 里,组件中的自定义属性优先级高于 Mixin 中的自定义属性。

2.3 自定义属性合并策略

自定义属性的优先级可以调整,我们来看下面的例子

    const myMixin = {
        num : 2
    }
    
    const app = Vue.createApp({
        num : 1, 

        mixins:[myMixin],

        template:`
            <div>
                <div>{{this.$options.num}}</div>
            </div>
        `
    });

    app.config.optionMergeStrategies.num = (mixinValue, appValue) => {
        return mixinValue || appValue; // 意思是先使用 mixinValue,如果 mixinValue 不存在,再使用 appValue
    }

 这个例子中,我们使用 app.config.optionMergeStrategies.num,对自定义属性 num 的优先级进行了调整。

3. 综述

今天聊了一下 VUE3 中的全局 Mixin 与 自定义属性合并策略,希望可以对大家的工作有所帮助,下一节我们继续讲 Vue 中的高级语法,敬请期待

欢迎帮忙点赞、评论、转发、加关注 :)

关注追风人聊Java,这里干货满满,都是实战类技术文章,通俗易懂,轻松上手。

4. 个人公众号

追风人聊Java,欢迎大家关注


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK