首页 > 技术文章 > vue之mixin理解与使用

MrSlow 2021-07-08 10:42 原文

我们有一对不同的组件,它们的作用是通过切换状态(Boolean类型)来展示或者隐藏模态框或提示框。这些提示框和模态框除了功能相似以外,没有其他共同点:它们看起来不一样,用法不一样,但是逻辑一样。

// 模态框
      const Modal = {
        template: '#modal',
        data() {
          return {
            isShowing: false
          }
        },
        methods: {
          toggleShow() {
            this.isShowing = !this.isShowing;
          }
        },
        components: {
          appChild: Child
        }
      }

      // 提示框
      const Tooltip = {
        template: '#tooltip',
        data() {
          return {
            isShowing: false
          }
        },
        methods: {
          toggleShow() {
            this.isShowing = !this.isShowing;
          }
        },
        components: {
          appChild: Child
        }
      }

 

我们可以在这里提取逻辑并创建可以被重用的项:

  •   const toggle = {
             data() {
               return {
                 isShowing: false
               }
             },
             methods: {
               toggleShow() {
                 this.isShowing = !this.isShowing;
               }
             }
           }
    
           const Modal = {
             template: '#modal',
             mixins: [toggle],
             components: {
               appChild: Child
             }
           };
    
           const Tooltip = {
             template: '#tooltip',
             mixins: [toggle],
             components: {
               appChild: Child
             }
           };

    一个简单的小案例

  •  //mixin
      const hi = {
        mounted() {
          console.log('hello from mixin!')
        }
      }
    
      //vue instance or component
      new Vue({
        el: '#app',
        mixins: [hi],
        mounted() {
          console.log('hello from Vue instance!')
        }
      });
    
      //Output in console
      > hello from mixin!
      > hello from Vue instance!

     

推荐阅读