[Vue] 用 Mixin 來共用方法

itsems
itsems_frontend
Published in
2 min readJun 20, 2020
Photo by Esther Wilhelmsson on Unsplash
Outline:
1. Mixin 是什麼? (What's mixin?)
2. 基礎使用 (Basic usage)
3. 選項合併 (Option Merging)
4. 全局混入 (Global Mixin)

Mixin 是什麼? (What’s mixin?)

Mixin 是一種讓組件之間共用方法的方法,所有 component 的選項都可以拿來使用 (created, computed…),當 component 使用 mixin 時,mixin 本身的選項都會和 component 自己的選項混合在一起。

基礎使用 (Basic usage)

/myMixin.vue

/hello.vue

<script>
import myMxn from "./myMixin";
export default {
mixins: [myMxn],
};
</script>

run serve:

選項合併 (Option Merging)

Methods, Components and Directives

如果 mixin 和 component 本身的 Methods, Components and Directives 命名衝突了,那就會以 component 本身的為主。(data 也是)

Hooks

但是如果衝突的是 life cycle 的 hooks (e.g, created, mounted, updated…),那 mixin 的和 component 的動作會被塞進一個陣列一一執行, mixin 的優先

全局混入 (Global Mixin)

也可以全域宣告 Mixin,但是務必使用小心,因為會影響到整個 Vue 實例:

宣告完成之後就會在每一個頁面出現這個 console 的訊息了

內容若有任何錯誤,歡迎留言交流指教! 🐬

ref:
Mixins — Vue.js

--

--

itsems
itsems_frontend

Stay Close to Anything that Makes You Glad You are Alive.