Vue.component('button-counter', {
template: ' 我是默认内容 '
})
new Vue({
el: '#app',
template: '我是slot传⼊内容 ',
components:{buttonCounter}
})
Vue.component('button-counter', {
template:
'<div>
<slot>我是默认内容</slot>
<slot name='center'>我是默认中间内容</slot>
<slot name='buttom'>我是默认底部内容</slot>
</div>'
})
new Vue({
el: '#app',
template: '我是slot传⼊的底部内容 ',
components:{buttonCounter}
})
Vue.component('button-counter', {
template: ' 我是默认内容 '
})
new Vue({
el: '#app',
template: '我是slot传⼊内容 ',
components:{buttonCounter}
})
经过vue编译, 组件渲染函数会变成这样
(function anonymous( ) {
with(this){return _c('div',[_t("default",[_v("我是默认内容")])],2)}
})
⽽这个_t就是slot渲染函数:
function renderSlot (name, fallback, props, bindObject) {
// 得到渲染插槽内容的函数
var scopedSlotFn = this.$scopedSlots[name];
var nodes;
// 如果存在插槽渲染函数,则执⾏插槽渲染函数,⽣成nodes节点返回
// 否则使⽤默认值
nodes = scopedSlotFn(props) || fallback;
return nodes;
}
⽽scopedSlots其实就是递归解析各个节点, 获取slot:
function resolveSlots(children,context) {
if (!children || !children.length) {
return {}
}
var slots = {};
for (var i = 0, l = children.length; i < l; i++) {
var child = children[i];
var data = child.data;
// remove slot attribute if the node is resolved as a Vue slot node
if (data && data.attrs && data.attrs.slot) {
delete data.attrs.slot;
}
// named slots should only be respected if the vnode was rendered in the
// same context.
if ((child.context === context || child.fnContext === context) &&
data && data.slot != null
) {
// 如果slot存在(slot="header") 则拿对应的值作为key
var name = data.slot;
var slot = (slots[name] || (slots[name] = []));
// 如果是tempalte元素 则把template的children添加进数组中,这也就是为什么你写的
//template标签并不会渲染成另⼀个标签到⻚⾯
if (child.tag === 'template') {
slot.push.apply(slot, child.children || []);
} else {
slot.push(child);
}
} else {
// 如果没有就默认是default
(slots.default || (slots.default = [])).push(child);
}
}
// ignore slots that contains only whitespace
for (var name$1 in slots) {
if (slots[name$1].every(isWhitespace)) {
delete slots[name$1];
}
}
return slots
}
附Vue插槽实现原理
本质其实就是⼀个js对象,它可以包含我们组件中任意功能选项,如data、components、methods、created、computed等等
Tips
mixin的实现原理
export function mergeOptions(parent: Object, child: Object, vm?: Component): Object {
if (child.mixins) { // 判断有没有mixin 也就是mixin⾥⾯挂mixin的情况 有的话递归进⾏合并
for (let i = 0, l = child.mixins.length; i < l; i++) {
parent = mergeOptions(parent, child.mixins[i], vm)
}
}
const options = {}
let key
for (key in parent) {
mergeField(key) // 先遍历parent的key 调对应的strats[XXX]⽅法进⾏合并
}
for (key in child) {
if (!hasOwn(parent, key)) { // 如果parent已经处理过某个key 就不处理了
mergeField(key) // 处理child中的key 也就parent中没有处理过的key
}
}
function mergeField(key) {
const strat = strats[key] || defaultStrat
options[key] = strat(parent[key], child[key], vm, key) // 根据不同类型的options调⽤strats中不同的⽅法进⾏合并
}
return options
}
其实主要的逻辑就是合并mixin和当前组件的各种数据, 细分为四种策略:
strats.props =
strats.methods =
strats.inject =
strats.computed = function (
parentVal: ?Object,
childVal: ?Object,
vm?: Component,
key: string
): ?Object {
if (!parentVal) return childVal // 如果parentVal没有值,直接返回childVal
const ret = Object.create(null) // 创建⼀个第三⽅对象 ret
extend(ret, parentVal) // extend⽅法实际是把parentVal的属性复制到ret中
if (childVal) extend(ret, childVal) // 把childVal的属性复制到ret中
return ret
}
strats.data = function (parentVal, childVal, vm) {
return mergeDataOrFn(
parentVal, childVal, vm
)
};
function mergeDataOrFn(parentVal, childVal, vm) {
return function mergedInstanceDataFn() {
var childData = childVal.call(vm, vm) // 执⾏data挂的函数得到对象
var parentData = parentVal.call(vm, vm)
if (childData) {
return mergeData(childData, parentData) // 将2个对象进⾏合并
} else {
return parentData // 如果没有childData 直接返回parentData
}
}
}
function mergeData(to, from) {
if (!from) return to
var key, toVal, fromVal;
var keys = Object.keys(from);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
toVal = to[key];
fromVal = from[key];
// 如果不存在这个属性,就重新设置
if (!to.hasOwnProperty(key)) {
set(to, key, fromVal);
}
// 存在相同属性,合并对象
else if (typeof toVal == "object" && typeof fromVal == "object") {
mergeData(toVal, fromVal);
}
}
return to
}
function mergeHook(
parentVal: ?Array<Function>,
childVal: ?Function | ?Array<Function>
): ?Array<Function> {
return childVal
? parentVal
? parentVal.concat(childVal)
: Array.isArray(childVal)
? childVal
: [childVal]
: parentVal
}
LIFECYCLE_HOOKS.forEach(hook => {
strats[hook] = mergeHook
})
strats.components=
strats.directives=
strats.filters = function mergeAssets(
parentVal, childVal, vm, key
) {
var res = Object.create(parentVal || null);
if (childVal) {
for (var key in childVal) {
res[key] = childVal[key];
}
}
return res
}
插件就是指对Vue的功能的增强或补充
MyPlugin.install = function (Vue, options) {
// 1. 添加全局⽅法或 property
Vue.myGlobalMethod = function () {
// 逻辑...
}
// 2. 添加全局资源
Vue.directive('my-directive', {
bind(el, binding, vnode, oldVnode) {
// 逻辑...
}
...
})
// 3. 注⼊组件选项
Vue.mixin({
created: function () {
// 逻辑...
}
...
})
// 4. 添加实例⽅法
Vue.prototype.$myMethod = function (methodOptions) {
// 逻辑...
}
}
Vue.use(plugin, options);
import { toArray } from '../util/index'
export function initUse(Vue: GlobalAPI) {
Vue.use = function (plugin: Function | Object) {
const installedPlugins = (this._installedPlugins || (this._installedPlugins
= []))
if (installedPlugins.indexOf(plugin) > -1) {
return this
}
// additional parameters
const args = toArray(arguments, 1)
args.unshift(this)
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args)
} else if (typeof plugin === 'function') {
plugin.apply(null, args)
}
installedPlugins.push(plugin)
return this
}
}
``