UPDATE См. конце в вопроса
Ни когда не использовал TypeScript. Но понадобилось покопаться внутри компонента Vue, который реализован на TypeScript. Может быть этот синтаксис аналогичен и для JavaScript, я не знаю. Но мне неочень понятны некоторые строки.
Сначала размещу весь код компонента, это компонент Vue-Tabulator, непонятные строки пометил комментариями, а дальше написал вопросы по ним:
<script lang='ts'>
import {
Component, Prop, Vue, Watch, Model,
} from 'vue-property-decorator';
import { IntegrationOptions, UpdateStrategy } from '@/types';
import mergeWith from 'lodash.mergewith'
import merge from '../utilities/merge'
const Tabulator = require('tabulator-tables');
import eventFactory from '../feature/event-factory'
import cellEvents from '../feature/events/cell-events'
import rowEvents from '../feature/events/row-events'
@Component({
name: 'TabulatorComponent',
})
export default class TabulatorComponent extends Vue {
@Model('change', { default: () => [] })
public tableData?: Array<any>;
//1--------------
private tabulatorInstance: Tabulator | null = null;
get eventOptions(): Object {
const events = eventFactory.bind(this)
return {...events(rowEvents), ...events(cellEvents)}
}
//2--------------
@Prop({ default: () => ({}) })
private options?: Tabulator.Options;
//3--------------
@Prop({ default: () => ({ updateStrategy: UpdateStrategy.DATA }) })
private integration?: IntegrationOptions;
//4--------------
private resolvedOptions: Tabulator.Options = {};
public getInstance() {
return this.tabulatorInstance;
}
private createTable() {
this.tabulatorInstance = new Tabulator(
this.$refs.table,
this.resolvedOptions,
);
}
@Watch('options', { deep: true })
private updateOptions() {
this.resolvedOptions = {
...mergeWith(this.eventOptions, this.options, merge),
data: this.tableData,
};
this.createTable();
}
@Watch('tableData', { deep: true })
private updateData() {
//5--------------
if (this.tabulatorInstance) {
if (this.integration && this.integration.updateStrategy === UpdateStrategy.REPLACE) {
this.tabulatorInstance.replaceData(this.tableData);
} else if (this.integration && this.tableData
&& this.integration.updateStrategy === UpdateStrategy.UPDATE) {
this.tabulatorInstance.updateData(this.tableData);
} else {
this.tabulatorInstance.setData(this.tableData);
}
}
}
mounted() {
this.updateOptions();
}
}
Строки по каким возникли вопросы:
private tabulatorInstance: Tabulator | null = null; //1
Что значит вcе что после двоеточия?
поле tabulatorInstance может принимать тип Tabulator или null? Что за странная конструкция | null = null
private options?: Tabulator.Options; //2
Что значит оператор?:
private integration?: IntegrationOptions; //3
Здесь я знаю что IntegrationOptions это enum из другого файла
Чтов этом случае значит это объявление?
private resolvedOptions: Tabulator.Options = {}; //4
Похоже на 2, но почему то тут появилось= {}
if (this.tabulatorInstance) { //5
Как tabulatorInstance может оказаться незаполненным?
UPDATE:
В компоненте есть еще такой файл entry.ts. Точка входа для компонента. Я как понял, эта точка входа необходима для компонента, который будет подключаться как плагин к приложению, т.е. через Vue.use().
Понял из этого, все кроме последнего блока кода для чего принудительно вызывается функция install? Это так принято или это решение разработчика так реализовать?
import Vue from 'vue';
import TabulatorComponent from '@/components/TabulatorComponent.vue';
export { TabulatorComponent };
function install(VueApp: typeof Vue, options: any = {}) {
const name = options.name || 'VueTabulator';
VueApp.component(name, TabulatorComponent);
};
export default {
install,
};
if (typeof window !== 'undefined' && (<any>window).Vue && (<any>window).Vue === Vue) {
install((<any>window).Vue)
}
tabulatorInstance
типTabulator
или null и присваиваем значение null. 2: необязательность{}
- пустой объект. 5. Эм, так как изначально ему и присвоено значениеnull