Tips for displaying dynamic content in VueJS?

I'm currently working on an app that allows users to choose which type of vuetify element they want to display on the page. There are 4 options available for selection. My goal is to render the corresponding vuetify component when a user clicks on their chosen option. For example, if the user selects divider, a

<v-divider></v-divider>
should appear; for spacer, a
<v-spacer></v-spacer>
; for toolbar, a
<v-toolbar></v-toolbar>
; and for text, a <v-btn></v-btn> with text should be displayed. I'm struggling to figure out how to achieve this.

You can view a demo of the code in action on this CodePen link

new Vue({
  el: "#app",
  data() {
    return {
      elements: [{
          title: "Divider",
          value: "divider"
        },
        {
          title: "Spacer",
          value: "spacer"
        },
        {
          title: "Toolbar",
          value: "toolbar"
        },
        {
          title: "Text",
          value: "text"
        }
      ],
      selected: []
    };
  },
  methods: {
    renderElements() {
      console.log(this.selected);
      this.selected = [];
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5a2c2f3f2e333c231b2e30232f34329a373b39">[email protected]</a>/dist/vuetify.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="625152425558454b40556f72797765">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet" />

<div id="app">
  <v-app id="inspire">
    <v-container>
      <v-layout column>
        <v-flex v-for="el in elements" :key="el.value">
          <v-checkbox :value="el.value" v-model="selected" :label="el.title"></v-checkbox>
        </v-flex>
        <v-btn @click="renderElements"> Render Dynamic Elements</v-btn>
      </v-layout>
    </v-container>
  </v-app>
</div>

If anyone can provide guidance on this, it would be greatly appreciated.

Answer №1

If you're looking to incorporate dynamic components in your project, consider using dynamic components:

<component v-for="(el, i) in selected" :key="i" :is="el.value"></component>

new Vue({
  el: "#app",
   data() {
     return {
      elements: [
         {
          title: "Divider", 
          value: "v-divider"
        },
        {
          title: "Spacer", 
          value: "v-spacer"
        },
        {
          title: "Toolbar", 
          value: "v-toolbar"
        }, 
       { 
         title: "Text",
            value: "v-btn"
        }
      ],
      selected: []
    };
  },
  methods: {
    renderElements() {
    console.log(this.selected);
      this.selected = [];
    }
  }
 });
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/babel-polyfill/dist/polyfill.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="285e5d4d5c414e516819061d06191c">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b4c2c1d1c0ddd2cdf4859a819a859085ca85ddcac7">[email protected]</a>/dist/vuetify.min.js"></script>


<div id="app">
  <v-app id="inspire">
    <v-container>
      <v-layout column>

        <v-flex v-for="el in elements" :key="el.value">
          <v-checkbox :value="el" v-model="selected" :label="el.title">
          </v-checkbox>
        </v-flex>
        <v-btn @click="renderElements"> Render Dynamic Elements</v-btn>
                
        <component v-for="(el, i) in selected" :key="i" :is="el.value"></component>
      </v-layout>
    </v-container>
  </v-app>
</div>

Answer №2

new Vue({
  el: "#app",
  data() {
    return {
      elements: [
        {
          title: "Divider",
          value: "v-divider",
          show: false
        },
        {
          title: "Spacer",
          value: "v-spacer",
          show: false
        },
        {
          title: "Toolbar",
          value: "v-toolbar",
          show: false
        },
        {
          title: "Text",
          value: "v-btn",
          show: false
        }
      ],
      selected: []
    };
  },
  methods: {
    renderElements() {
      console.log(this.selected);
      for(let i=0; i<this.elements.length; i++)
      {
        this.elements[i].show = this.selected.includes(i);
      }
    }
  }
});
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/babel-polyfill/dist/polyfill.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/example/vuetify.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/example/vuetify.min.js"></script>

<div id="app">
  <v-app id="inspire">
    <v-container>
      <v-layout column>
        <v-checkbox v-for="(item, i) in elements"
            :key="i"
            :label="item.title"
            :value="i"
            v-model="selected"
         ></v-checkbox>
        
        <v-btn @click="renderElements"> Render Dynamic Elements</v-btn>
        <component v-for="(item, i) in elements" :key="i + 10" :is="item.value" v-if="item.show">{{ item.title }}</component>
      </v-layout>
    </v-container>
  </v-app>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Resolve the Prototype_Pollution vulnerability detected by Checkmarx

When executing the code line window.location.search.substring(1) with the word 'substring(1)', an error related to Prototype_Pollution occurs. This error is caused by assigning external properties without proper validation, which can lead to obje ...

What are the placeholders for the "localIdentName" query tag in a custom CSS-loader for Webpack?

Just starting out with Webpack and experimenting with the css-loader. I came across the option to specify a localIdentName query tag on the Github page under "Local Scope". This tag allows us to define our own custom values for how classes should be named ...

What occurs when Click events are triggered on an <object> element?

I have set up a div, and inside that container, I embedded an SVG image using object (which I plan to manipulate later...). <div id="click-me"> some random Text <object data="some.svg" /> </div> Next, I added event listeners for t ...

Retrieve characteristics from removed or replicated entities and allocate them to different entities

Looking for a bit of assistance with an array transformation: [ {Code:13938, Country:699, Name:"Crocs", codeProduct:1} {Code:13952, Country:699, Name:"Polo Club", codeProduct:14} {Code:13952, Country:699, Name:"Polo Club", codeProduct:1} {Code ...

Showing a text value from a Github Gist on a Hugo website

I seem to be struggling with a seemingly simple task and I can't figure out what I'm missing. Any assistance would be greatly appreciated. I am working on generating a static site using Hugo. On one of my pages, I want to implement a progress ba ...

Forward the jsp to the servlet before navigating to the following page

Issue: After submitting the JSP form on Page1, it redirects to a server-side JSP page but appears as a blank page in the browser. Instead, I want it to redirect to Page2 which includes a list box that highlights the newly created item. Seeking help with t ...

Utilizing a combination of HTML, AJAX, and PHP, transfer an HTML input array via AJAX to a PHP webpage

Despite trying numerous similar solutions, none of them have proven effective for my issue. Within a form, users can input an unspecified amount of select options that can be added as needed using AJAX. My goal is to post this array to a PHP page via AJAX ...

Guide to generating interactive material-ui components within a react application?

I am facing a challenge in creating a dynamic mui grid element triggered by a button click in a React component. When attempting to create let newGrid = document.createElement('Grid'), it does not behave the same way as a regular div creation. D ...

Ways to activate a function upon validation of an email input type

Within my HTML form, there is an input type="email" field that requires a valid email pattern for acceptance. I am attempting to send an AJAX request to the server to confirm whether the entered email already exists in the database after it has been verif ...

Link dynamic Vue image source from node_modules

I am currently working on a Vue component that displays an SVG image from my node modules based on a specific image name or key provided by an API. If I directly specify the source image like ~cryptocurrency-icons/svg/color/eur.svg, it loads without any i ...

Deleting Firestore ancestor documents and sub-collections that do not exist

My goal is to tidy up my collection data. The collection I'm working with is named "teams". Within this collection, there is a sub-collection called "players". I used a basic delete query in Firestore to remove the document under ...

How can I troubleshoot email validation issues in Vue.js?

<button type="submit" class="register-button" :class="(isDisabled) ? '' : 'selected'" :disabled='isDisabled' v-on:click=" isFirstScreen ...

Vetur is experiencing issues with template functionality, such as not properly checking data and methods

I have incorporated the vetur extension into my Visual Studio Code for a Vue project using TypeScript. I recently discovered that vetur has the capability to perform type checks within the template tag for props, methods, and even variables. However, in ...

Please select the option to choose all values

Currently, I am working on implementing a select option feature on my webpage. I have integrated PHP into it to ensure that the selected option remains unchanged after submission. My goal is to include a value of "any" so that when the user chooses "ANY," ...

Problem concerning the window object in a React functional component

Hey there, I am currently facing a situation where I need to access the window object within my React component in order to retrieve some information from the query string. Here is an excerpt of what my component code looks like: export function MyCompone ...

Is it possible to identify the buttons array in Fancybox 3 using inline data attributes?

Are you able to outline the specific buttons you need for an inline version of Fancybox 3? For instance: <a :data-src="someImage.jpg" data-fancybox data-fancybox-buttons="['zoom', 'share', 'download&apo ...

Arrange an asynchronous function in Node.js

I have been attempting to set up a schedule for an asynchronous function (with async/await return type) to run every two minutes. Although I have tried using the generic setInterval, as well as various node modules such as node-schedule, cron, node-cron, ...

Is there a way to load a JSON configuration file and have the Vue application wait for it to be loaded?

My usual setup involves: a webpack-packed Vue app a dedicated configuration file to set up the app The configuration file is excluded from the deployment package generated by webpack, as it contains server-specific details (such as database credentials) ...

Having trouble aligning a div in the middle of a slick-slider item using flex styling

I've created a slick slider component in Vue, and I'm facing an issue with centering a circular div inside each of the slider items. Despite trying to align and justify center along with adding margin:auto for horizontal centering, I can't s ...

jquery mouse event does not register on touch-based devices

I have a mouse move event set up to scroll a div. However, when I try to access the functionality using a tab it does not work. How can I integrate this functionality onto a touch device? $(document).ready(function(){ $('#tim').on('mous ...