定义minxin
//minxin.js
var myMixin = {
data: function () {
return {
message: 'hello',
foo: 'abc'
}
},
created: function () {
console.log('混入对象的钩子被调用')
},
methods: {
foo1: function () {
console.log('foo1');
},
conflicting: function () {
console.log('from mixin');
}
}
}
export default myMixin;
页面使用
<template>
<div class="mixin" v-wechat-title="$route.meta.title"></div>
</template>
<script>
import myMixin from "./minxin.js";
export default {
name: "mixin",
mixins: [myMixin], //引入mixins
data() {
return {
message: "goodbye",
bar: "def"
};
},
components: {},
created() {
console.log("组件钩子被调用");
// => "混入对象的钩子被调用"
// => "组件钩子被调用"
// ------表明混入里的钩子函数先与组件的钩子函数先调用
// ------如果组件里有就用组件里的 没有就用混入里的
console.log(this.$data); // => { message: "goodbye", foo: "abc", bar: "def" }
},
watch: {},
//值为对象的选项,例如 methods、components 和 directives,将被合并为同一个对象。两个对象键名冲突时,取组件对象的键值对。
mounted() {
this.foo1(); // => "foo1"
this.bar1(); // => "bar1"
this.conflicting(); // => "from self"
},
methods: {
bar1: function() {
console.log("bar1");
},
conflicting: function() {
console.log("from self");
}
},
computed: {}
};
</script>
<style scoped lang="scss">
</style>
全局混入
//mian.js
Vue.mixin('混入的js');
自定义属性
//自定义一个属性
new Vue({
data: function() {
return {
};
},
created: function () {
},
mounted() {},
methods: {
},
myOption: '自定义属性!'
})
//针对自定义属性做操作(使用混入)
Vue.mixin({
myOption:'minxi里自定义参数',
created: function () {
var myOption = this.$options.myOption
if (myOption) {
console.log(myOption)
}
}
})
自定义选项合并策略
main.js
//1自定义选项将使用默认策略,即简单地覆盖已有值。如果想让自定义选项以自定义逻辑合并,可以向 Vue.config.optionMergeStrategies 添加一个函数:
Vue.config.optionMergeStrategies.myOption = function (toVal, fromVal) {
// 返回合并后的值
}
//2对于多数值为对象的选项,可以使用与 methods 相同的合并策略:
var strategies = Vue.config.optionMergeStrategies
strategies.myOption = strategies.methods
//3 可以在 Vuex 1.x 的混入策略里找到一个更高级的例子:
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)
}
}