这一篇开始读源码,初始化部分。
const draggableComponent = {
name: "draggable",
inheritAttrs: false,//vue的api,组件传入属性,props没接收的话,会自动被$attrs变量接收;值为false就不会自动接收
props,
data() {
return {
transitionMode: false,
noneFunctionalComponentMode: false
};
},
render(h) { //vue api,生成dom
const slots = this.$slots.default;
this.transitionMode = isTransition(slots);//检测组件包裹的,是不是TransitionGroup标签
const { children, headerOffset, footerOffset } = computeChildrenAndOffsets( slots,this.$slots, this.$scopedSlots );
//组件内可定义具名插槽,slot="header". slot="footer"
this.headerOffset = headerOffset;//获取具名插槽header插槽个数
this.footerOffset = footerOffset;//获取具名插槽footer插槽个数
//$attrs,是vue api,传入组件的数据,不用props接收就会自动被$attrs收集
//componentData,传入组件的数据
//获取以上两者的值
const attributes = getComponentAttributes(this.$attrs, this.componentData);
return h(this.getTag(), attributes, children);//h函数创建dom。参数:标签名,传递数据,子节点数组
},
created() { //检验参数,提示
if (this.list !== null && this.value !== null) {
console.error("Value and list props are mutually exclusive! Please set one or another." );
}
if (this.element !== "div") {
console.warn("Element props is deprecated please use tag props instead. See https://github.com/SortableJS/Vue.Draggable/blob/master/documentation/migrate.md#element-props" );
}
if (this.options !== undefined) {
console.warn("Options props is deprecated, add sortable options directly as vue.draggable item, or use v-bind. See https://github.com/SortableJS/Vue.Draggable/blob/master/documentation/migrate.md#options-props" );
}
},
mounted() {
this.noneFunctionalComponentMode =this.getTag().toLowerCase() !== this.$el.nodeName.toLowerCase() &&
!this.getIsFunctional();
if (this.noneFunctionalComponentMode && this.transitionMode) {
throw new Error(`Transition-group inside component is not supported. Please alter tag value or remove transition-group. Current tag value: ${this.getTag()}` );
}
const optionsAdded = {}; //保存事件函数
eventsListened.forEach(elt => {
optionsAdded["on" + elt] = delegateAndEmit.call(this, elt);
});
eventsToEmit.forEach(elt => {
optionsAdded["on" + elt] = emit.bind(this, elt);
});
//保存传入组件的数据$attrs
const attributes = Object.keys(this.$attrs)
.reduce((res, key) => { //Object.keys(this.$attrs)转数组
res[camelize(key)] = this.$attrs[key];
return res;
}, {});
//合并各种参数,其中this.options已经废弃,见mounted里的 if (this.options !== undefined) {}
const options = Object.assign({}, this.options, attributes, optionsAdded, {
onMove: (evt, originalEvent) => {
return this.onDragMove(evt, originalEvent);
}
});
!("draggable" in options) && (options.draggable = ">*");
//参数中draggable,是sortable.js中,用于初始化的参数。列表被li或ul包裹值为'>li',否则为 '>*'
this._sortable = new Sortable(this.rootContainer, options);//底层使用了sortable.js
this.computeIndexes();
},