vue-组件式函数和混入

组件式函数

  • 使用方式
// mixin.js
import {ref} from 'vue'
export const com = function (num) {
    const x = ref(0);
    const y = ref(0)
    const c = ref(0)
  setTimeout(()=>{
    c.value = num + 10
  },1000)
  window.addEventListener('mousemove',(e)=>{
    x.value = e.pageX
    y.value = e.pageY
  })
  return {x,y,c}
}
<template>
  <div>1111</div>
  <div>{{num.x}}</div>
  <div>{{num.y}}</div>
  <div>{{num.c}}</div>
</template>
<script>
  import {com} from "@/views/mixins/mixin";
  // import {mixin} from "@/views/mixins/mixin";
  export default {
    // mixins: [mixin],
    data() {
      return {
        num: {
          x: 0,
          y: 0,
          c: 0
        }
      }
    },
    created() {
      this.num = com(1);
    },
  }
</script>

混入(mixin)

  • 定义方式:
// js或ts类型文件 mixin.js
export const mixin= {
  created(){
    window.addEventListener('mousemove',(e) => {
      this.num.x = e.pageX
      this.num.y = e.pageY
    })
  },
	data(){
		return {
			num:{
		        x:0,
	        	y:0
	        }
		}
	}
}
//  vue文件 

```javascript

<template>
    <div>1111</div>
    <div>{{num.x}}</div>
    <div>{{num.y}}</div>
</template>
  import {mixin} from "@/views/mixins/mixin";
  export default {
  	mixins:[mixin],
  }
</script>
mixin特点
  • 当属性值与组件属性值重复时,以组件属性为准。
  • 生命周期为mixin优先执行。
mixin缺点。

官方建议使用组件式函数,vue3之所以去兼容mixin是因为方便项目迁移。

  • 数据来源不清晰。多个mixin的导入会导致数据来源不明确。组合式的ref+解构模式让数据来源变得清晰可见。
  • 命名冲突。多个开发者的mixin有可能会导致属性命名重复。而组件式函数可以在解构变量的时候进行重命名。
  • 耦合性多个mixin共享的属性名进行相互作用,这样就形成了隐式耦合性。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值