vue3和vue2中mixins的使用解析
前言
vue的mixins里面放公共的js方法,但是vue3之后使用方法還是有些改變,這里來(lái)羅列下他們的區(qū)別。
Vue2
1、封裝的mixin方法

export const homeSensors = {
mounted() {
this.$sensors.track('teacherHomePageview')
},
methods:{
abc(){
alert(1)
}
}
}2、具體頁(yè)面引用 abc.vue
import { homeSensors } from '@/mixins/sensorsMixin'export default {
mixins: [taskAssign],
}3、具體頁(yè)面使用 abc.vue
created() {
this.abc() //mixin里面的具體方法
}, vue3官方入口(個(gè)人建議,不要再mixin用setup)
一、封裝mixin里面具有setup
注意:
vue3的官方統(tǒng)計(jì)mixin方法有兩種,全局和具體組件使用,均沒(méi)有支持在mixin的js文件中使用setup, 在里面直接寫(xiě)入setup階段,是不能直接獲取到的,如果我們想要用setup,需要換一種思路,引入js的思路
具體步驟
1、封裝方法 common.js

//setup中調(diào)用的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、頁(yè)面具體使用
// vue頁(yè)面中引入
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 (官方支持用法)
官方入口:點(diǎn)我
Mixin 提供了一種非常靈活的方式,來(lái)分發(fā) Vue 組件中的可復(fù)用功能。一個(gè) mixin 對(duì)象可以包含任意組件選項(xiàng)。當(dāng)組件使用 mixin 對(duì)象時(shí),所有 mixin 對(duì)象的選項(xiàng)將被“混合”進(jìn)入該組件本身的選項(xiàng)。
例子:
// 定義一個(gè) mixin 對(duì)象
const myMixin = {
created() {
this.hello()
},
methods: {
hello() {
console.log('hello from mixin!')
}
}
}
// 定義一個(gè)使用此 mixin 對(duì)象的應(yīng)用
const app = Vue.createApp({
mixins: [myMixin]
})
app.mount('#mixins-basic') // => "hello from mixin!"具體使用
1、封裝方法 common.js

//setup中調(diào)用的mixins方法
import { computed, ref } from 'vue'
export const common = {
mounted(){
alert('我是mounted的方法')
},
}2、頁(yè)面具體使用
import {common} from '../../../mixins/common'
mixins: [common],3、頁(yè)面效果:刷新以后

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue中this.$router和this.$route的區(qū)別及push()方法
這篇文章主要給大家介紹了關(guān)于Vue中this.$router和this.$route的區(qū)別及push()方法的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05
Vue動(dòng)態(tài)組件與內(nèi)置組件淺析講解
閑話少說(shuō),我們進(jìn)入今天的小小五分鐘學(xué)習(xí)時(shí)間,前面我們了解了vue的組件,我們本文主要是講解vue的動(dòng)態(tài)組件和內(nèi)置組件,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08
element-ui組件table實(shí)現(xiàn)自定義篩選功能的示例代碼
這篇文章主要介紹了element-ui組件table實(shí)現(xiàn)自定義篩選功能的示例代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-03-03
vue中g(shù)etters的使用與四個(gè)map方法的使用方式
這篇文章主要介紹了vue中g(shù)etters的使用與四個(gè)map方法的使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01

