vue3和vue2中mixins的使用解析
前言
vue的mixins里面放公共的js方法,但是vue3之后使用方法還是有些改變,這里來羅列下他們的區(qū)別。
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的官方統(tǒng)計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 提供了一種非常靈活的方式,來分發(fā) 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、頁面效果:刷新以后
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Vue中this.$router和this.$route的區(qū)別及push()方法
這篇文章主要給大家介紹了關于Vue中this.$router和this.$route的區(qū)別及push()方法的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-05-05element-ui組件table實現自定義篩選功能的示例代碼
這篇文章主要介紹了element-ui組件table實現自定義篩選功能的示例代碼,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-03-03