vue#defineComponent JavaScript Examples
The following examples show how to use
vue#defineComponent.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.js From vue-json-schema-form with Apache License 2.0 | 7 votes |
numberTimeComponent = component => defineComponent({
inheritAttrs: false,
setup(props, { attrs, slots }) {
return () => {
const {
isNumberValue, isRange, value, ...otherAttrs
} = attrs;
// antdv moment format 必须接受字符串时间戳
const newValue = isNumberValue
? (isRange
? (value || []).map(item => (typeof item === 'number' ? String(item) : item))
: typeof value === 'number' ? String(value) : value
)
: value;
const trueAttrs = {
...attrs,
value: newValue,
'onUpdate:value': function updateValue(upValue) {
if (isNumberValue) {
upValue = isRange ? upValue.map(item => +item) : +upValue;
}
otherAttrs['onUpdate:value'].call(this, upValue);
}
};
return h(resolveComponent(component), trueAttrs, slots);
};
}
})
Example #2
Source File: index.jsx From ant-simple-pro with MIT License | 6 votes |
Counter = defineComponent({
setup(props, { expose }) {
const count = ref(0)
expose({ count })
function onClick() {
count.value += 1
}
return () => {
return (
<div>
<p>some contents...</p>
<p>{count.value}</p>
<a-button type="primary" onClick={onClick}>
增加
</a-button>
</div>
)
}
}
})
Example #3
Source File: vue3Utils.js From vue-json-schema-form with Apache License 2.0 | 6 votes |
modelValueComponent = (component, {
model = 'value'
} = {}) => defineComponent({
inheritAttrs: false,
setup(props, { attrs, slots }) {
return () => {
const {
modelValue: value,
'onUpdate:modelValue': onUpdateValue,
...otherAttrs
} = attrs;
// eg: 'a-input'
return h(resolveComponent(component), {
[model]: value,
[`onUpdate:${model}`]: onUpdateValue,
...otherAttrs
}, slots);
};
}
})
Example #4
Source File: index.js From vue-json-schema-form with Apache License 2.0 | 6 votes |
globalOptions = {
WIDGET_MAP,
COMPONENT_MAP: {
form: defineComponent({
inheritAttrs: false,
setup(props, { attrs, slots }) {
const formRef = ref(null);
if (attrs.setFormRef) {
onMounted(() => {
attrs.setFormRef(formRef.value);
});
}
return () => {
// eslint-disable-next-line no-unused-vars
const { setFormRef, ...otherAttrs } = attrs;
return h(vueUtils.resolveComponent('el-form'), {
ref: formRef,
...otherAttrs
}, slots);
};
}
}),
formItem: 'el-form-item',
button: 'el-button',
popover: 'el-popover'
},
HELPERS: {
// 是否mini显示 description
isMiniDes(formProps) {
return formProps && ['left', 'right'].includes(formProps.labelPosition);
}
}
}
Example #5
Source File: index.js From p2p-tunnel with GNU General Public License v2.0 | 6 votes |
files.keys().forEach((key, index) => {
const md = files(key).default;
const name = `about-${index}`;
pages.push({
path: `/${name}.html`,
name: name,
meta: { name: path.basename(key, path.extname(key)) },
component: defineComponent({
name: name,
render () {
return <v-md-preview text={md}></v-md-preview>;
}
})
});
});
Example #6
Source File: vue3-highcharts.js From vue3-highcharts with MIT License | 5 votes |
vueHighcharts = defineComponent({
name: 'VueHighchart',
props: {
type: {
type: String,
default: 'chart',
},
options: {
type: Object,
required: true,
},
redrawOnUpdate: {
type: Boolean,
default: true,
},
oneToOneUpdate: {
type: Boolean,
default: false,
},
animateOnUpdate: {
type: Boolean,
default: true,
},
},
setup(props, { emit }) {
const chartRef = ref(null);
const chart = ref(null);
const { options } = toRefs(props);
if (options.value && Highcharts[props.type]) {
watch(options, (newValue) => {
if (chart.value) {
chart.value.update(newValue, props.redrawOnUpdate, props.oneToOneOnUpdate, props.animateOnUpdate);
emit('updated');
}
}, { deep: true });
onMounted(() => {
chart.value = Highcharts[props.type](chartRef.value, options.value, () => {
emit('rendered');
});
});
onUnmounted(() => {
if (chart.value) chart.value.destroy();
emit('destroyed');
});
} else if (!props.options) {
console.warn('The "options" parameter is required.');
} else {
console.warn(`${props.type} is not a valid highcharts type or has not been imported`);
}
// Rather than returning a render function here. We'll return the chart ref and highcharts
// instance so there exposed.
return {
chartRef,
chart,
};
},
render() {
return h('div', {
class: 'vue-highcharts',
ref: 'chartRef',
});
},
})
Example #7
Source File: vuedraggable.js From vue.draggable.next with MIT License | 4 votes |
draggableComponent = defineComponent({
name: "draggable",
inheritAttrs: false,
props,
emits,
data() {
return {
error: false
};
},
render() {
try {
this.error = false;
const { $slots, $attrs, tag, componentData, realList, getKey } = this;
const componentStructure = computeComponentStructure({
$slots,
tag,
realList,
getKey
});
this.componentStructure = componentStructure;
const attributes = getComponentAttributes({ $attrs, componentData });
return componentStructure.render(h, attributes);
} catch (err) {
this.error = true;
return h("pre", { style: { color: "red" } }, err.stack);
}
},
created() {
if (this.list !== null && this.modelValue !== null) {
console.error(
"modelValue and list props are mutually exclusive! Please set one or another."
);
}
},
mounted() {
if (this.error) {
return;
}
const { $attrs, $el, componentStructure } = this;
componentStructure.updated();
const sortableOptions = createSortableOption({
$attrs,
callBackBuilder: {
manageAndEmit: event => manageAndEmit.call(this, event),
emit: event => emit.bind(this, event),
manage: event => manage.call(this, event)
}
});
const targetDomElement = $el.nodeType === 1 ? $el : $el.parentElement;
this._sortable = new Sortable(targetDomElement, sortableOptions);
this.targetDomElement = targetDomElement;
targetDomElement.__draggable_component__ = this;
},
updated() {
this.componentStructure.updated();
},
beforeUnmount() {
if (this._sortable !== undefined) this._sortable.destroy();
},
computed: {
realList() {
const { list } = this;
return list ? list : this.modelValue;
},
getKey() {
const { itemKey } = this;
if (typeof itemKey === "function") {
return itemKey;
}
return element => element[itemKey];
}
},
watch: {
$attrs: {
handler(newOptionValue) {
const { _sortable } = this;
if (!_sortable) return;
getValidSortableEntries(newOptionValue).forEach(([key, value]) => {
_sortable.option(key, value);
});
},
deep: true
}
},
methods: {
getUnderlyingVm(domElement) {
return this.componentStructure.getUnderlyingVm(domElement) || null;
},
getUnderlyingPotencialDraggableComponent(htmElement) {
//TODO check case where you need to see component children
return htmElement.__draggable_component__;
},
emitChanges(evt) {
nextTick(() => this.$emit("change", evt));
},
alterList(onList) {
if (this.list) {
onList(this.list);
return;
}
const newList = [...this.modelValue];
onList(newList);
this.$emit("update:modelValue", newList);
},
spliceList() {
// @ts-ignore
const spliceList = list => list.splice(...arguments);
this.alterList(spliceList);
},
updatePosition(oldIndex, newIndex) {
const updatePosition = list =>
list.splice(newIndex, 0, list.splice(oldIndex, 1)[0]);
this.alterList(updatePosition);
},
getRelatedContextFromMoveEvent({ to, related }) {
const component = this.getUnderlyingPotencialDraggableComponent(to);
if (!component) {
return { component };
}
const list = component.realList;
const context = { list, component };
if (to !== related && list) {
const destination = component.getUnderlyingVm(related) || {};
return { ...destination, ...context };
}
return context;
},
getVmIndexFromDomIndex(domIndex) {
return this.componentStructure.getVmIndexFromDomIndex(
domIndex,
this.targetDomElement
);
},
onDragStart(evt) {
this.context = this.getUnderlyingVm(evt.item);
evt.item._underlying_vm_ = this.clone(this.context.element);
draggingElement = evt.item;
},
onDragAdd(evt) {
const element = evt.item._underlying_vm_;
if (element === undefined) {
return;
}
removeNode(evt.item);
const newIndex = this.getVmIndexFromDomIndex(evt.newIndex);
// @ts-ignore
this.spliceList(newIndex, 0, element);
const added = { element, newIndex };
this.emitChanges({ added });
},
onDragRemove(evt) {
insertNodeAt(this.$el, evt.item, evt.oldIndex);
if (evt.pullMode === "clone") {
removeNode(evt.clone);
return;
}
const { index: oldIndex, element } = this.context;
// @ts-ignore
this.spliceList(oldIndex, 1);
const removed = { element, oldIndex };
this.emitChanges({ removed });
},
onDragUpdate(evt) {
removeNode(evt.item);
insertNodeAt(evt.from, evt.item, evt.oldIndex);
const oldIndex = this.context.index;
const newIndex = this.getVmIndexFromDomIndex(evt.newIndex);
this.updatePosition(oldIndex, newIndex);
const moved = { element: this.context.element, oldIndex, newIndex };
this.emitChanges({ moved });
},
computeFutureIndex(relatedContext, evt) {
if (!relatedContext.element) {
return 0;
}
const domChildren = [...evt.to.children].filter(
el => el.style["display"] !== "none"
);
const currentDomIndex = domChildren.indexOf(evt.related);
const currentIndex = relatedContext.component.getVmIndexFromDomIndex(
currentDomIndex
);
const draggedInList = domChildren.indexOf(draggingElement) !== -1;
return draggedInList || !evt.willInsertAfter
? currentIndex
: currentIndex + 1;
},
onDragMove(evt, originalEvent) {
const { move, realList } = this;
if (!move || !realList) {
return true;
}
const relatedContext = this.getRelatedContextFromMoveEvent(evt);
const futureIndex = this.computeFutureIndex(relatedContext, evt);
const draggedContext = {
...this.context,
futureIndex
};
const sendEvent = {
...evt,
relatedContext,
draggedContext
};
return move(sendEvent, originalEvent);
},
onDragEnd() {
draggingElement = null;
}
}
})
Example #8
Source File: index.jsx From ant-simple-pro with MIT License | 4 votes |
QueryTemplate = defineComponent({
emits: ['submit', 'reset'],
props: {
options: {
type: Array,
default: () => [
{
title: '日期',
fieldName: 'date',
type: 'timeRangeSelection',
optionList: [],
labelName: '',
valueName: '',
childrenName: ''
}
]
},
name: {
type: String,
default: ''
}
},
setup(props, { emit }) {
const formRef = ref()
// default form fields
const defaultForm = {}
const form = reactive(defaultForm)
onMounted(() => {
for (let i = 0; i < props.options.length; i++) {
const item = props.options[i] // eslint-disable-line
defaultForm[item.fieldName] = typeof item.defaultValue !== 'undefined' ? item.defaultValue : ''
}
const filteredOptions = props.options.filter(item => item.defaultValue) || []
if (filteredOptions.length) {
filteredOptions.forEach(item => {
if (item.type === 'monthDatePicker') {
Object.assign(form, {
[item.fieldName]: moment(item.defaultValue, 'YYYY-MM')
})
}
// else {
// Object.assign(form, {
// [item.fieldName]: moment(item.defaultValue)
// })
// }
})
}
})
function onFinish(value) {
const formData = Object.assign({}, value)
try {
props.options.forEach(item => {
const rangeValue = value[item.fieldName]
switch (item.type) {
case 'showTimeRangePicker': {
formData[item.fieldName] =
rangeValue && rangeValue.length
? rangeValue.map(item => {
if (typeof item === 'string') {
return item
}
return item.format('YYYY-MM-DD HH:mm:ss')
})
: []
break
}
case 'timeRangeSelection': {
formData[item.fieldName] =
rangeValue &&
rangeValue.length &&
rangeValue.map(item => {
if (typeof item === 'string') {
return item
}
return item.format('YYYY-MM-DD')
})
break
}
case 'monthDatePicker': {
formData[item.fieldName] = rangeValue && moment(rangeValue).format('YYYY-MM')
break
}
case 'dayDatePicker': {
formData[item.fieldName] = rangeValue && rangeValue.format && rangeValue.format('YYYY-MM-DD')
break
}
default: {
// ...
}
}
})
} catch (error) {
console.log(error)
}
emit('submit', formData)
}
function onReset() {
formRef.value?.resetFields()
emit('reset', toRaw(form))
}
function disabledDate(current) {
return current && current > moment().endOf('day')
}
function getTemplateByType(type, opts) {
const templateObj = {
input: <a-input v-model={[form[opts.fieldName], 'value']} placeholder={opts.placeholder || '请填写'}></a-input>,
select: (
<a-select
v-model={[form[opts.fieldName], 'value']}
placeholder={opts.placeholder || '请填写'}
onChange={opts.onChange}
>
{opts.optionList?.map((item, index) => (
<a-select-option key={index} value={item[opts.valueName]}>
{item[opts.labelName]}
</a-select-option>
))}
</a-select>
),
cascader: (
<a-cascader
v-model={[form[opts.fieldName], 'value']}
options={opts.optionList}
placeholder={opts.placeholder || '请填写'}
fieldNames={{
label: opts.labelName,
value: opts.valueName,
children: opts.childrenName
}}
changeOnSelect
></a-cascader>
),
timeRangeSelection: (
<TimeRangeSelection
v-model={[form[opts.fieldName], 'value']}
placeholder={opts.placeholder}
></TimeRangeSelection>
),
showTimeRangePicker: (
<a-range-picker
v-model={[form[opts.fieldName], 'value']}
onChange={opts.onChange}
placeholder={opts.placeholder}
showTime
></a-range-picker>
),
monthDatePicker: (
<a-month-picker
v-model={[form[opts.fieldName], 'value']}
onChange={opts.onChange}
placeholder={opts.placeholder || '请填写'}
disabledDate={disabledDate}
></a-month-picker>
),
dayDatePicker: (
<a-date-picker
v-model={[form[opts.fieldName], 'value']}
mode="date"
onChange={opts.onChange}
placeholder={opts.placeholder || '请填写'}
disabledDate={disabledDate}
></a-date-picker>
)
}
const template = templateObj[type]
if (template) {
return template
}
return (
<a-input
v-model={[form[opts.fieldName], 'value']}
onChange={opts.onChange}
placeholder={opts.placeholder || '请填写'}
></a-input>
)
}
return () => {
return (
<a-form ref={formRef} model={form} onFinish={onFinish} class="search-template" name={props.name}>
<a-row gutter={[15, 15]}>
{props.options.map((item, index) => (
<a-col xs={24} sm={12} md={12} lg={8} xl={props.options.length > 3 ? 6 : 8} key={index}>
<a-form-item
label={item.title}
name={item.fieldName}
data-label={item.title}
data-name={item.fieldName}
>
{getTemplateByType(item.type, item)}
</a-form-item>
</a-col>
))}
<a-col xs={24} sm={12} md={12} lg={8} xl={props.options.length > 3 ? 6 : 8}>
<a-form-item>
<a-button type="primary" htmlType="submit">
查询
</a-button>
<a-button class="ml10" onClick={onReset}>
重置
</a-button>
</a-form-item>
</a-col>
</a-row>
</a-form>
)
}
}
})
Example #9
Source File: index.js From vue-json-schema-form with Apache License 2.0 | 4 votes |
globalOptions = {
WIDGET_MAP,
COMPONENT_MAP: {
form: defineComponent({
inheritAttrs: false,
setup(props, { attrs, slots }) {
// 处理 labelPosition 参数和layout之间转换
const labelPositionMap = {
top: {
layout: 'vertical'
},
left: {
layout: 'horizontal',
labelAlign: 'left'
},
right: {
layout: 'horizontal',
labelAlign: 'right'
}
};
// 返回当前的 form ref
const formRef = ref(null);
if (attrs.setFormRef) {
onMounted(() => {
// form组件实例上附加一个 validate 方法
formRef.value.$$validate = (callBack) => {
formRef.value.validate().then((res) => {
callBack(true, res);
}).catch((err) => {
callBack(false, err.errorFields);
});
};
attrs.setFormRef(formRef.value);
});
}
return () => {
const {
// eslint-disable-next-line no-unused-vars
setFormRef, labelPosition, labelWidth, model, ...otherAttrs
} = attrs;
if (otherAttrs.inline) {
Object.assign(otherAttrs, {
layout: 'inline',
// labelCol: undefined,
// wrapperCol: undefined
});
}
return h(vueUtils.resolveComponent('a-form'), {
ref: formRef,
model: model.value,
...labelPositionMap[labelPosition || 'top'],
...otherAttrs,
colon: false
}, slots);
};
}
}),
formItem: defineComponent({
inheritAttrs: false,
setup(props, { attrs, slots }) {
const formItemRef = ref(null);
return () => {
const { prop, rules, ...originAttrs } = attrs;
return h(vueUtils.resolveComponent('a-form-item'), {
...originAttrs,
ref: formItemRef,
// 去掉callback 使用promise 模式
rules: (rules || []).map(validateRule => ({
...validateRule,
validator(rule, value) {
return validateRule.validator.apply(this, [rule, value]);
}
})),
name: prop ? prop.split('.') : prop
}, {
...slots,
default: function proxySlotDefault() {
// 解决 a-form-item 只对第一个子元素进行劫持,并监听 blur 和 change 事件,如果存在第一个元素description无法校验
// @blur="() => {$refs.name.onFieldBlur()}"
// @change="() => {$refs.name.onFieldChange()}"
return slots.default.call(this, {
onBlur: () => {
if (formItemRef.value.$el.querySelector('.genFromWidget_des')) {
// 存在 description,需要手动触发校验事件
formItemRef.value.onFieldBlur();
}
},
onChange: () => {
if (formItemRef.value.$el.querySelector('.genFromWidget_des')) {
// 存在 description,需要手动触发校验事件
formItemRef.value.onFieldChange();
}
}
});
}
});
};
}
}),
button: 'a-button',
popover: defineComponent({
setup(props, { attrs, slots }) {
return () => h(vueUtils.resolveComponent('a-popover'), attrs, {
default: slots.reference,
content: slots.default,
});
}
}),
},
HELPERS: {
// 是否mini显示 description
isMiniDes(formProps) {
return formProps && (
['left', 'right'].includes(formProps.labelPosition)
|| formProps.layout === 'horizontal' || formProps.inline === true
);
}
}
}
Example #10
Source File: index.js From vue-json-schema-form with Apache License 2.0 | 4 votes |
globalOptions = {
WIDGET_MAP,
COMPONENT_MAP: {
form: defineComponent({
inheritAttrs: false,
setup(props, { attrs, slots }) {
// 处理 labelPosition 参数和 label-placement 之间的关系
const labelPositionMap = {
top: {
labelAlign: 'left',
labelPlacement: 'top',
},
left: {
labelAlign: 'left',
labelPlacement: 'left',
},
right: {
labelAlign: 'right',
labelPlacement: 'left',
}
};
const formRef = ref(null);
if (attrs.setFormRef) {
onMounted(() => {
// form组件实例上重置一个 validate 方法
formRef.value.$$validate = (callBack) => {
formRef.value.validate((errors) => {
if (errors) {
return callBack(false, errors);
}
return callBack(true);
});
};
attrs.setFormRef(formRef.value);
});
}
return () => {
const {
// eslint-disable-next-line no-unused-vars
setFormRef, labelPosition, model, ...otherAttrs
} = attrs;
return h(vueUtils.resolveComponent('n-form'), {
ref: formRef,
model: model.value, // 不会自动解包
...labelPositionMap[labelPosition || 'top'],
...otherAttrs
}, slots);
};
}
}),
formItem: defineComponent({
inheritAttrs: false,
setup(props, { attrs, slots }) {
return () => {
const { prop, rules, ...originAttrs } = attrs;
const childAttrs = {
...originAttrs,
path: prop,
rule: (rules || []).map(validateRule => ({
trigger: validateRule.trigger,
asyncValidator(rule, value, callback) {
return validateRule.validator(rule, value, callback);
}
})),
};
return h(vueUtils.resolveComponent('n-form-item'), childAttrs, slots);
};
}
}),
button: 'n-button',
// popover: ,
popover: defineComponent({
setup(props, { attrs, slots }) {
return () => h(vueUtils.resolveComponent('n-popover'), attrs, {
trigger: slots.reference,
default: slots.default,
});
}
}),
},
HELPERS: {
// 是否mini显示 description
isMiniDes(formProps) {
return formProps && ['left', 'right'].includes(formProps.labelPosition);
}
}
}