Vue mixin All In One
Vue mixin All In One
vue 2.x
- data 同名覆盖, components 优先级高
var mixin = {
data: function () {
return {
// ❌
message: 'hello',
foo: 'abc'
}
}
}
new Vue({
mixins: [mixin],
data: function () {
return {
// ✅
message: 'goodbye',
bar: 'def'
}
},
created: function () {
console.log(this.$data)
// => { message: "goodbye", foo: "abc", bar: "def" }
}
})
- lifecycle hooks 同名共存,先执行 mixin, 后执行 components
var mixin = {
created: function () {
console.log('mixin hook called', 1);
}
}
new Vue({
mixins: [mixin],
created: function () {
console.log('component hook called', 2);
}
})
// => "mixin hook called"
// => "component hook called"
- methods 同名覆盖, components 优先级高
var mixin = {
methods: {
foo: function () {
console.log('foo')
},
conflicting: function () {
// ❌
console.log('from mixin');
}
}
}
var vm = new Vue({
mixins: [mixin],
methods: {
bar: function () {
console.log('bar')
},
conflicting: function () {
// ✅
console.log('from self');
}
}
})
vm.foo() // => "foo"
vm.bar() // => "bar"
vm.conflicting() // => "from self"
Note that the same merge strategies are used in Vue.extend()
.
- Vue.mixin
global mixin
谨慎使用全局mixins,因为它会影响创建的每个Vue实例,包括第三方组件。
在大多数情况下,仅应将其用于自定义选项处理,如下例所示。
// inject a handler for `myOption` custom option
Vue.mixin({
created: function () {
var myOption = this.$options.myOption
if (myOption) {
console.log(myOption)
}
}
})
new Vue({
myOption: 'hello!'
})
// => "hello!"
最好将它们作为插件发布以避免重复应用。
https://vuejs.org/v2/guide/plugins.html
demo
https://www.vuemastery.com/courses/next-level-vue/mixins/
合并自定义选项时,它们将使用默认策略来覆盖现有值。
const merge = Vue.config.optionMergeStrategies.computed
Vue.config.optionMergeStrategies.vuex = function (toVal, fromVal) {
if (!toVal) return fromVal
if (!fromVal) return toVal
return {
getters: merge(toVal.getters, fromVal.getters),
state: merge(toVal.state, fromVal.state),
actions: merge(toVal.actions, fromVal.actions)
}
}
https://vuejs.org/v2/api/#optionMergeStrategies
vue 3.x
https://v3.vuejs.org/guide/mixins.html#custom-option-merge-strategies
Composition API
https://v3.vuejs.org/guide/composition-api-introduction.html
refs
https://vuejs.org/v2/guide/mixins.html
https://v3.vuejs.org/guide/mixins.html#mixins
Vue.mixin
https://vuejs.org/v2/api/#Vue-mixin
Vue.extend
https://vuejs.org/v2/api/#Vue-extend
https://vuejs.org/v2/api/#Vue-component
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/14427343.html
未经授权禁止转载,违者必究!