vue3基础-mixin使用

mixin特点:

  • 组件 data 优先级 高于 mixin 的data优先级
  • 组件 methods 优先级 高于 mixin 的methods优先级
  • 声明周期函数,先执行 mixin 里面的,再执行组件里面的
  • 局部mixin,需要在组件中注册 mixins: [myMixin]
  • 全局mixin 无需在组件中注册,自动注入。

定义局部mixin

和定义局部组件类似,支持data,methods以及声明周期函数。
mixin.js

const myMixin = {
  data() {
    return {
      msg: 'hello vue3'
    }
  },
  created() {
    console.log('mixin created');
  },
  methods: {
    handleClick() {
      console.log('mixin', this.msg);
    }
  }
}

组件中使用:
组件中data,methods优先级都会高于mixin

 const app = Vue.createApp({
   mixins: [myMixin], // 注册mixin
   template: `<div>
     {{msg}}  
     <button @click="handleClick">点击</button>
   </div>`,
   created() {
     console.log('app created');
   },
   data() {
     return {
       msg: 'hello world'
     }
   },
   methods: {
     handleClick() {
       console.log('app', this.msg);
     }
   },
 })

定义全局mixin(不推荐)

// 全局mixin 无需在组件中注册,自动注入。
app.mixin({
  mounted() {
    console.log('这是一个全局的mixin');
  }
})

调整mixin中属性的优先级

const myMixin = {
  msg: 'hello mixin ~'
}
// $options 组件注册的所有选项都会在 $options 中
const app = Vue.createApp({
  mixins: [myMixin],
  msg: 'hello app ~',
  template: `
    <div>
      {{ $options.msg }}  
    </div>`,
})

// ** 调整mixin中属性(如:msg)的优先级,使mixin的优先级高级组件的
app.config.optionMergeStrategies.msg = (mixinValue, appValue) => {
  return mixinValue || appValue;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值