【问题标题】:Vue3 Creating Component Instances Programmatically on button clickVue3在按钮单击时以编程方式创建组件实例
【发布时间】:2021-01-22 20:23:12
【问题描述】:

在 vue2 中很容易:

<template>
 <button :class="type"><slot /></button>
</template>
<script>
 export default {
   name: 'Button',
   props: [ 'type' ],
 }
</script>
import Button from 'Button.vue'
import Vue from 'vue'

var ComponentClass = Vue.extend(Button)
var instance = new ComponentClass()

instance.$mount() // pass nothing
this.$refs.container.appendChild(instance.$el)

扩展 + 创建实例。但是在 vue3 中它已被删除。还有什么办法?

【问题讨论】:

  • 为什么要以这种方式(通过 DOM 操作)而不是标准的 Vue 习惯用法(即模板或渲染函数)来实例化组件?
  • @tony19 因为它只是一个例子,真正的生产方式等待后端答案并用后端数据渲染它

标签: javascript vue.js vuejs3


【解决方案1】:
import {defineComponent,createApp} from 'vue'

buttonView = defineComponent({
    extends: Button, data() {
        return {
            type: "1111"
        }
    }
})

const div = document.createElement('div');
this.$refs.container.appendChild(div);
createApp(buttonView ).mount(div)

【讨论】:

  • 我如何以编程方式v-bind:?我有type: var,但是当我更改var的值时,它不会更新
  • 你能解释一下this.$refs.container.appendChild(div);中的this是什么吗?
  • 这种情况下依赖注入不起作用
  • @Artemiy 您如何收听创建的“应用程序”上的事件以及当您不再需要它时如何销毁它?在 Vue 2 中,像 instance.$on('event', cb) 这样的东西是可能的,并且销毁一个简单的 instance.$destroy() 是可能的。你现在会怎么做?
  • @darkylmnx 请提出新问题,这与上述主题无关
【解决方案2】:

试试下面的代码:

import Button from 'Button.vue'


const CompB = {
  extends: Button
}

this.$refs.container.appendChild(CompB.$el)

【讨论】:

  • 请您提供更详细的答案。答案有点难理解
猜你喜欢
  • 2021-08-13
  • 2017-06-21
  • 2013-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-16
  • 2017-06-17
  • 2013-05-23
相关资源
最近更新 更多