【发布时间】:2019-09-24 01:28:10
【问题描述】:
我正在使用 Typescript 编写 VueJS (2.5.22) 应用程序并尝试在运行时动态添加组件。我遇到了 Typescript 的两个问题。添加子组件作为命名槽并订阅从子组件发出事件。我可以通过附加子组件来解决插槽,但是我想使用命名插槽。感谢您对插槽的任何输入。
我仍在尝试解决父组件订阅子事件和更新父组件中的属性的第二个问题。
子组件将发出“更新值”。如何在父组件上动态订阅这个事件?
谢谢,
请为:vuejs-component vuejs-dynamic-component vuejs-typescript vuejs-emit 创建标签
parent component adding dynamically at run-time in created method
<div>
<p>Dynamic components</p>
<div ref="controls"></div>
</div>
export default class ParentComponent extends Vue {
public $refs: Vue['$refs'] & {
controls: HTMLElement
}
public $slots: Vue['$slots'] & {
TextBox: TextBox
}
vuejs created method
--------------------
const labelControlContainerClass = Vue.extend(LabelControlContainer)
const textBoxClass = Vue.extend(TextBox)
const fields = table.fields
for (const key in fields) {
if (fields.hasOwnProperty(key)) {
const element = fields[key]
if (element.fieldType === 'Char') {
const textBoxInstance = new textBoxClass({
// props
propsData: {
value: '',
placeholder: element.translatedCaption,
name: key
},
// how to subscript to "update-value" event???
})
textBoxInstance.$mount()
const instance = new labelControlContainerClass({
// props
propsData: {
caption: element.translatedCaption,
bold: false
},
})
instance.$mount()
instance.$el.appendChild(textBoxInstance.$el) // add child component, try adding named slots, but didn't work
this.$refs.controls.appendChild(instance.$el)
}
}
}
}
label component with slot. named slot didn't worked
<template>
<div class="controlContainer" :class="{vertial: labelTop}">
<span v-bind:class="{bold: bold}" class=".controlContainer__cisLabel">{{caption}}</span>
<slot name='control'></slot>
<slot></slot>
</div>
</template>
<script lang='ts'>
import Vue from 'vue'
import { Component, Prop } from 'vue-property-decorator'
@Component({
})
export default class LabelControlContainer extends Vue {
@Prop({ type: String, default: '' }) public caption: string
@Prop({ type: Boolean, default: true }) public bold: boolean
@Prop({ type: Boolean, default: false }) public labelTop: boolean
}
</script>
child component that is going to added to slot and emit on value change
export default class TextBox extends Vue {
@Prop({ type: String, default: 'placeholder text' }) public placeholder: string
@Prop({ type: Object, default: () => ({}) }) public attributes: any
@Prop({ type: Boolean, default: false }) public readonly: boolean
@Prop({ type: String, default: 'text' }) public mode: string
@Prop({ type: Boolean, default: true }) public isValid: boolean
@Prop({ type: String, default: '' }) public value: string
@Prop({ type: String, default: '' }) public name: string
@Prop({ type: Boolean, default: false }) public setFocus: boolean
private default = {}
private unlockable: boolean = this.readonly
private valueChanged(data: any): void {
this.$emit('update-value', data.value, this.name)
}
}
【问题讨论】:
标签: vue.js