gpt4 book ai didi

vue.js - 如何以编程方式添加 Vue 3 组件?

转载 作者:行者123 更新时间:2023-12-04 12:14:00 24 4
gpt4 key购买 nike

Vue 3 没有 Vue.extend() 方法,所以这里的例子不起作用:
https://css-tricks.com/creating-vue-js-component-instances-programmatically/
我试过这个解决方案:
https://jsfiddle.net/jamesbrndwgn/fsoe7cuy/
但它会在控制台中引起警告:
Vue 收到了一个组件,它是一个响应式对象。这会导致不必要的性能开销,应该通过使用 markRaw 标记组件来避免。或使用 shallowRef而不是 ref .
enter image description here
那么,在 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" class="tag-input" 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)
设置 Prop 或插槽因使用而有所不同 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")
}
})

关于vue.js - 如何以编程方式添加 Vue 3 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66170232/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com