如何以编程方式添加Vue3组件?
Vue 3 没有 Vue.extend() 方法,所以这里的例子不起作用:https ://css-tricks.com/creating-vue-js-component-instances-programmatically/
我试过这个解决方案:https :
//jsfiddle.net/jamesbrndwgn/fsoe7cuy/
但它会在控制台中引起警告:
Vue 收到了一个组件,它是一个响应式对象。这会导致不必要的性能开销,应该通过用markRaw或shallowRef代替标记组件来避免ref。
在此处输入图片说明
那么,在 Vue 3 中动态(以编程方式)添加组件的正确方法是什么?
上传任务标签管理器.vue
<template>
<button @click="addTag()" type="button">Add new tag</button>
<br>
<div>
<div v-for="child in children" :key="child.name">
<component :is="child"></component>
</div>
</div>
</template>
<script>
import UploadTaskTag from "./UploadTaskTag";
export default {
name: "UploadTaskTagManager",
components: {UploadTaskTag},
data() {
return {
children: []
}
},
methods: {
addTag() {
this.children.push(UploadTaskTag);
},
}
}
</script>
上传任务标签.vue
<template>
<div>
<select @change="onChangeTag($event)" v-model="currentTag">
<option v-for="tag in getAllTags()" :key="tag.tag_name" :value="tag">{{tag.tag_name}}</option>
</select>
<input maxlength="16" ref="inputField"/>
<button @click="removeTag($event)" type="button">-</button>
<br>
</div>
</template>
<script>
export default {
name: "UploadTaskTag",
data() {
return {
tags: [],
currentTag: {}
}
},
methods: {
onChangeTag(event) {
this.$refs.inputField.value = this.currentTag.tag_name;
},
getAllTags() {
return this.$store.state.allTags;
},
removeTag() {
this.$el.parentElement.removeChild(this.$el)
},
getValue(fieldIndex) {
let tag = this.tags[fieldIndex];
return tag ? tag.tag_name : "";
},
}
}
</script>
回答
只是使用createApp而不是Vue.extend
这里的一个简单的 vue3 组件的编程示例
import Button from 'Button.vue'
import { createApp } from "vue"
// Creating the Instance
// use createApp https://v3.vuejs.org/api/global-api.html#createapp
var ComponentApp = createApp(Button)
import Button from "./Button.vue"
// inserting to dom
const wrapper = document.createElement("div")
ComponentApp.mount(wrapper)
document.body.appendChild(wrapper)
set props or slot 在使用上有点不同h,https://v3.vuejs.org/api/global-api.html#h
import Button from 'Button.vue'
import { createApp, h } from "vue"
var ComponentApp = createApp({
setup () {
return () => h(Button, {type: "primary"}, "default slot as children")
}
})