如何使用Vue.js在页面上实时添加不同的组件

问题描述 投票:0回答:1

我的目标是允许用户根据他们在select元素中的选择,从不同的组件动态构建表单。例如,他们可以选择添加标题,然后添加段落,再添加另一个标题,等等。每个“部分”都是一个单独的组件。

我知道这种事情以前曾被问过,但是我只是进入Vue的第二天,我想我已经完成了90%的工作-我只是想念一些东西。我认为我坚持的是如何在我的应用程序数据中添加组件以允许Vue渲染它。

以下是相关标记:

<div id="creator">
    <template v-for="part in existingParts">
        <component :is="part"></component>
    </template>
    <select class = "custom-select" id = "new-part-chooser" v-model="newPart" v-on:change="addPart">
        <option disabled value = "">Add a new part</option>
        <option
            v-for="part in possibleParts"
            v-bind:value="part.toLowerCase()"
            >{{ part }}</option>
    </select>
    <?php
        // These simply bring in the templates for the components
        // I know this isn't standard practice but... one thing at a time
        include 'component-heading.html';
        include 'component-paragraph.html';
    ?>
</div>

和我的JavaScript文件:

Vue.component("part-heading",{
    data:function(){
        return {
            text: ""
        }
    },
    template:"#component-heading-template"
});
Vue.component("part-paragraph",{
    data:function(){
        return {
            text: ""
        }
    },
    template:"#component-paragraph-template"
});

const Creator = new Vue({
    el:"#creator",
    data:{
        newPart:"",
        possibleParts:[
            "Heading",
            "Paragraph"
        ],
        existingParts:[]
    },
    methods:{
        addPart:function(e){
            /*** This is where I'm stuck - what do I push here? ***/
            this.existingParts.push();
        }
    }
});

我已经阅读了所有文档,而Google则无所适从,但是每种设置似乎都不同,以至于我不知道如何应用它。

vue.js vuejs2 vue-component
1个回答
0
投票

我缺少这样的事实,在标记中,:is指令导致Vue创建与existingParts中的元素名称匹配的组件。因此,将push()-“部分标题”引入到existingParts中会使Vue呈现“部分标题”组件的实例。

© www.soinside.com 2019 - 2024. All rights reserved.