Vue官方文档梳理之全局配置官方文档梳理之全局配置
主要介绍了Vue官方文档梳理之全局配置,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随
小编过来看看吧
本文主要介绍了Vue官方文档梳理之全局配置,分享给大家,也给自己留个笔记。具体如下:
optionMergeStrategies
用于自定义选项的合并策略,Vue已经预定义了一些自己配置项的合并策略,如下图所示。
比如props、methods、computed就是同一个策略:子配置项会覆盖父级配置项。源码如下:
var strats = config.optionMergeStrategies;
strats.props =
strats.methods =
strats.computed = function (parentVal, childVal) {
if (!childVal) { return Object.create(parentVal || null) }
if (!parentVal) { return childVal }
var ret = Object.create(null);
extend(ret, parentVal);
extend(ret, childVal);
return ret
};
什么时候才会用到这些配置的合并规则呢?查阅源码,发现只要调用mergeOptions时,就会用到上面的策略。总结下来有以
下几种场景:
1. 使用了 Vue.mixin 或 mixins 配置项
2. 使用了 Vue.extend 或 extends 配置项或Vue.component(背后实际上是调用了Vue.extend)
3. new Vue() 或 new Vue.extend()
单独使用一个时,也会触发合并规则,但是只会有child包含配置项,所以不需要合并。只有当多个一起使用时,比如
Vue.compeont 和 extends 、mixins 配置项一起使用,这个时候就parent和child都会有相同的配置项,这时候也才有所谓的合
并,举个完整的例子来说明上述的场景。
Vue.config.optionMergeStrategies['customOption'] = function (toVal, fromVal) {
console.log(toVal, fromVal)
if (!toVal) return fromVal
if (!fromVal) return toVal
// toVal 和 fromVal 同时存在,表明此时parent和child都包含配置型
return toVal + '&' + fromVal
}
Vue.extend({
customOption: 'Vue.extend'
})
Vue.component('custom', {
customOption: 'Vue.component'
})
var vm = new Vue({