混入(Mixins)是一種在Vue組件中重用代碼的方式。它允許你定義一些可復用的選項對象,然后將這些選項合并到不同的組件中。混入可以用于在多個組件之間共享邏輯、方法、生命周期鉤子等。
示例:
<!DOCTYPE html>
<html><head><title>Vue mixin demo</title><script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
</head><body><div id="app"><my-component></my-component></div><script>// 定義一個混入對象const myMixin = {data() {return {message: 'Hello from mixin!'}},methods: {greet() {console.log(this.message)}}}Vue.component('my-component', {mixins: [myMixin],template: '<div>{{message}}</div>',created() {this.greet()}})var vm = new Vue({el: '#app',});</script>
</body></html>
選項合并
當組件和混入對象的選項同名時,數據對象data中同名選項以組件的優先,進行遞歸合并;同名鉤子函數則會被合并為數組,它們都會執行,且混入對象的鉤子函數先執行。
對于methods、components、directives這些值為對象的選項,同名鍵的合并例子如下:
<!DOCTYPE html>
<html><head><title>Vue mixin demo</title><script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
</head><body><div id="app"></div><script>const mixin = {methods: {greet() {console.log('Hello from Mixin!');},sayHello() {console.log('Mixin says hello!');},}};var Component = Vue.extend({methods: {greet() {console.log('Hello from extend!');},sayHello() {console.log('extend says hello!');},sayGoodbye() {console.log('extend says goodbye!');}}});new Component({mixins: [mixin],methods: {greet() {console.log('Hello from component!');},},created() {this.greet(); // Output: Hello from component!this.sayHello(); // Output: Mixin says hello!this.sayGoodbye(); // Output: extend says goodbye!}});</script>
</body></html>
由上面得出選項合并優先級:new Component > mixins > Vue.extend。
全局混入
全局混入會影響每一個Vue實例。
使用Vue.mixin({})
方法創建全局混入。
盡量避免使用全局混入,這樣會導致邏輯分散、代碼難以閱讀、維護困難。
?自定義選項合并策略
下面是一個示例:
const customMergeStrategies=Vue.config.optionMergeStrategies
customMergeStrategies.customOption=function(parentVal,childVal){if(!childVal) return parentValif(!parentVal) return childVal//合并邏輯,可根據需要修改return parentVal.concat(childVal)
}
關鍵是了解Vue.config.optionMergeStrategies的作用,它用于幫助我們自定義某個選項的合并策略函數,該函數第一個參數是父組件的該選項值,第二個參數是子組件的該選項值。