简体   繁体   中英

How to create a dropdown list dynamically using Vuejs? Or any general component

I have been trying to dynamically add a Vue component into my template while the app is running. I know that fundamentally, people usually prefer not to use this type of concept with Vuejs but my current project requires me to do it.

Let's look at a simplified code:

<template>
    <div>
        <object-container>
            <-- I basically want to add a component here -->
        </object-container>
    </div>
</template>

For example once the user clicks on a button, or changes a certain option from the application. My application needs to generate new components according to the input. For our sake, let's assume that we only want to generate a single dropdown list.

Example would be something like: https://v2.vuejs.org/v2/guide/forms.html#Select

However, this needs to be generated dynamically and the options will come from the inputs of the application.

Beyond the simple example of select and options. How can I dynamically generate a vue component that I have created? For example, if I make a component called myDropDown , how can I generate this component dynamically similar to the simple select example? I would assume that it is fairly similar.

Basically I want a functionality similar to jQuery like in this question: How to create dropdown list dynamically using jQuery?

Edit:

I wanted to add some questions similar to mine, unfortunately, none of these really give an answer, I really have no choice but to dynamically generate new components that can not be previously prepared.

append vue js component using jquery

Append dynamic vue component after specific element

There are more examples that have a very similar question, and my question can be tagged as duplicate but I couldn't find any solutions at all.

You can try use the following code

 Vue.component('my-row', { props: ['title'], template:`<option>{{title}}</option>`, }) new Vue({ el: '#box-select', data:{ newTodoText: '', items: [ { id: 1, title: 'Do the dishes', }, { id: 2, title: 'Take out the trash', }, { id: 3, title: 'Mow the lawn' } ] }, methods:{ onChange(key) { this.newTodoText = "id:"+this.items[key-1].id+"/title:"+this.items[key-1].title; } } })
 <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script> <div id="box-select"> <select @change="onChange($event.target.value)"> <option is="my-row" v-for="item in items" v-bind:title="item.title" v-bind:value="item.id" > </option> </select> <!-- <view-option v-for="item in items" :item="item" :key="item.id"></view-option> --> {{newTodoText}} </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM