vue代码复用方法 - Mixins

本文详细介绍了Vue.js中Mixins的使用方法,包括如何创建、导入和应用Mixins以实现代码复用,同时展示了Mixins在解决组件间业务逻辑复用问题时的应用案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Mixins 是 Vue.js 提供的,用于代码复用的非常有用的特性,尤其是针对函数的复用。Mixins 是混合的意思,Vue 实例引用 mixins 文件,mixins 对象中的公共方法会合并到 Vue 实例中被复用。

以下是完整的 mixins 使用示例,请按照以下列举的规则使用 mixins。

示例
// toggleMixin.js
const toggleMixin = {
  data() {
    return {
      isShowing: false
    }
  },
  methods: {
    $_toggleMixin_toggleShow() {
      this.isShowing = !this.isShowing;
    }
  }
}
 
export { toggleMixin }

// example.vue
<template>
  <div>
    <h3 @click="$_toggleMixin_toggleShow">
      <span v-if="isShowing">Click Me Again</span>
      <span v-else>Click Me Please</span>
    </h3>
  </div>
</template>
 
<script>
import { toggleMixin } from "toggleMixin";
export default {
  mixins: [toggleMixin]  // 引入 toggleMixin 对象,data 和 methods 都会合并到当前组件中
};
</script>

规则1 - 业务逻辑复用代码放在 components/mixins 目录下

components
|-- mixins
|---- {name}Mixin.js

规则2 - Mixin 文件以及 Mixin 对象以 Mixin 后缀结尾
规则3 - 一个 Mixin 对象一个独立的文件
规则4 - Mixin 对象中的方法始终使用 $_ 前缀,并附带 Mixin 对象名以回避和其它作者的冲突

参加《编码规范》

进阶阅读 - 如果 mixin 对象与组件合并冲突怎么办?

如果选项的值是函数,则混合为一个数组;如果选项的值是对象,则混合为一个新对象,两个对象键名冲突时,取组件对象的键值对。

case1

选项的值是函数

示例

// mixin
const hi = {
    mounted() {
        console.log('hi from mixin!')
    }
}
 

//vue instance or component
new Vue({
    mixins: [hi],
    mounted() {
        console.log('hi from Vue instance!')
    }
});
 
// hi from mixin!
// hi from Vue instance!

说明

mounted 钩子函数同名,混合后在 Vue 组件中的结果是一个数组,拥有两个 mounted 钩子函数,并且优先执行 mixin 中的钩子函数。
执行结果是先执行 mixin 中的 mounted 函数,然后执行 vue 组件中的 mounted 函数。
所以最终日志打印结果是:

hi from mixin!
hi from Vue instance!

case2

选项的值是对象

示例

//mixin
const hi = {
    methods: {
      sayHi: function() {
        console.log('hi from mixin!')
      }
    },
    mounted() {
      this.sayHi()
    }
  }
    
  //vue instance or component
  new Vue({
    mixins: [hi],
    methods: {
      sayHi: function() {
        console.log('hi from Vue instance!')
      }
    },
    mounted() {
      this.sayHi()
    }
  })
    
// hi from Vue instance!
// hi from Vue instance!

说明

methods 是一个对象,混合后在 Vue 组件中的结果是一个新对象,其中 mixin 中的 sayHi 函数会被 Vue 组件中的同名函数重写。

执行结果是先执行 mixin 中的 mounted 函数,并调用 Vue 实例中的 sayHi 函数;然后执行 Vue 实例中的 mounted 函数并调用 Vue 实例中的 sayHi函数。

所以最终日志打印结果是:

hi from Vue instance!
hi from Vue instance!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值