iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >vue3和vue2中mixins的使用解析
  • 317
分享到

vue3和vue2中mixins的使用解析

2024-04-02 19:04:59 317人浏览 独家记忆
摘要

目录前言Vue21、封装的mixin方法2、具体页面引用 abc.vue3、具体页面使用 abc.vuevue3官方入口(个人建议,不要再mixin用setup)一、封装mixin里

前言

vue的mixins里面放公共的js方法,但是vue3之后使用方法还是有些改变,这里来罗列下他们的区别。

Vue2

1、封装的mixin方法

export const homeSensors = {
  mounted() {
    this.$sensors.track('teacherHomePageview')
  },
    methods:{
        abc(){
            alert(1)
        }
    }
}

2、具体页面引用 abc.vue

import { homeSensors } from '@/mixins/sensorsMixin'
export default {
  mixins: [taskAssign],
 
}

3、具体页面使用 abc.vue

created() {
    this.abc()   //mixin里面的具体方法
  },  

vue3官方入口(个人建议,不要再mixin用setup)

一、封装mixin里面具有setup

注意:

vue3的官方统计mixin方法有两种,全局和具体组件使用,均没有支持在mixin的js文件中使用setup,    在里面直接写入setup阶段,是不能直接获取到的,如果我们想要用setup,需要换一种思路,引入js的思路

具体步骤

1、封装方法  common.js 

//setup中调用的mixins方法
import { computed, ref } from 'vue'
export const common =  {
  alertCon(content) {
    if(content){
      alert(content)
    }else{
      alert(1)
    }
  },
  setup(){
    const count = ref(1)
    const plusOne = computed(() => count.value + 1)
    function hello(){
      console.log('hello mixin'+plusOne.value)
    }
    return{
      count,
      plusOne,
      hello
    }
  }
}

2、页面具体使用

 
// vue页面中引入
import {common} from '../../../mixins/common'
export default{
  setup(){
    common.alertCon()
    const {count,plusOne,hello} = common.setup()
    hello()
    console.log(count.value, plusOne.value)
  }
}

二、不需要在mixin里面使用setup  (官方支持用法)

官方入口:点我

Mixin 提供了一种非常灵活的方式,来分发 Vue 组件中的可复用功能。一个 mixin 对象可以包含任意组件选项。当组件使用 mixin 对象时,所有 mixin 对象的选项将被“混合”进入该组件本身的选项。

例子:

// 定义一个 mixin 对象
const myMixin = {
  created() {
    this.hello()
  },
  methods: {
    hello() {
      console.log('hello from mixin!')
    }
  }
}
 
// 定义一个使用此 mixin 对象的应用
const app = Vue.createApp({
  mixins: [myMixin]
})
 
app.mount('#mixins-basic') // => "hello from mixin!"

具体使用

1、封装方法  common.js

//setup中调用的mixins方法
import { computed, ref } from 'vue'
export const common =  {
   mounted(){
    alert('我是mounted的方法')
  },
}

2、页面具体使用

import {common} from '../../../mixins/common'
mixins: [common],

3、页面效果:刷新以后

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: vue3和vue2中mixins的使用解析

本文链接: https://www.lsjlt.com/news/150202.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作