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

Tap here to switch between 2 jquery functions

Due to the deprecation of the toggle() method in jQuery version 1.8 and its removal in version 1.9, an alternative approach is needed for versions 1.11 and above. You can check out the documentation for more information. If you are looking to replicate th ...

What is the recommended approach for sending a null value to a mandatory property in a Vue.js component?

Setup: Vue.js (3.2) with Composition API, TypeScript, and Visual Studio Code File type.ts: export class GeographicCoordinate { latitude: number; longitude: number; altitude?: number; constructor(latitude: number, longitude: number, altitude?: num ...

Vue - The import statement cannot be used outside of a module context

I am currently working on developing a form that requires certain dependencies listed in the package.json file including vue, axios, and sweetalert. "dependencies": { "axios": "^0.19.0", "vue": "^2.6.10" ...

Building a JSON-powered navigation bar with Bootstrap 4

Looking to create a custom navigation bar using Bootstrap 4 and populate it with items from a JSON file. Despite researching various methods, there seems to be limited resources available on this topic. Any assistance or guidance would be greatly appreciat ...

Make sure to choose the radio button that corresponds to the desired title value, as this will be automatically added to the input text

Visit this link for a live example. <div class='liveExample'> <input type="radio" name="gender" value="Mr." checked>Mr. <input type="radio" name="gender" value="Mrs.">Mrs. <p>First name: <input data-bind=&ap ...

Executing a node (console) command from a JavaScript file using AJAX on click

Hey, I'm a beginner in node.js and I have a question: Imagine I have a web application with a button. When the user clicks this button, I want to execute a node console command (e.g. node socket.io). Here's my attempt using jQuery: $( ".button ...

What is the process for uninstalling Vue CLI 2 from my system?

I am looking to start a new vue project using @vue/cli . It seems that the vue/cli has been updated to version 3. The documentation I found is located at https://i.sstatic.net/iDEJ1.png and I am currently running ubuntu 17.10, attempting to uninstall vue ...

Ways to arrange choices alphabetically in Vue.js

Is there a way to order the options alphabetically in my quiz app? I followed the code from this source, but I need the responses listed in alphabetical order. How can I achieve that? Here is the question list sent to the template Response var quiz = { ...

What sets Fetch Promise apart in terms of delivery success?

Struggling with using strapi in my project, as the fetch function returns a promise instead of JSON data This is my code : const [products, setProducts] = useState([]); useEffect(() => { (async () => { try { l ...

The script fails to work correctly when displaying the data

Last night, I finally cracked the code on how to transfer data from my form on the index page to the content page, and then display the results inside the content div back on the index page. However, a new challenge has emerged. My Javascript function (re ...

Switching on and off a class in Next.js

I'm a beginner with Next.js and React framework. My question is regarding toggling a class. Here's my attempt in plain JS: function toggleNav() { var element = document.getElementById("nav"); element.classList.toggle("hidde ...

Tips for implementing a live filter on an HTML table using JavaScript without the need to refresh the webpage

I successfully implemented these table filtering codes using plain JavaScript that I found on W3schools. The code filters table data based on input text and includes a select dropdown for additional filtering options. However, I encountered some issues whe ...

express node struggling to locate bootstrap.js file

I am working with a specific directory structure within my project: projectName | -.sencha/ | - app/ | - view | - controller | - store | - saas | - server/ | -server.js ...

Using Vue/Nuxt.js to compute the cumulative sum of hierarchically structured JSON data

When using Nuxt async data, I am retrieving a JSON object that includes a nested array in the following structure: "topic_list": { "topics": [ { "id": 9148, "title": "A", "views": 12 }, { "id": 3228, ...

What is the best way to utilize the GET Method with a hashtag incorporated into the URL?

For instance: www.sample.com#?id=10 Currently, I am not able to retrieve any value from $_GET['id']. Despite my attempt to eliminate the hashtag from the URL using JavaScript, no change occurs: $(document).ready(function(){ $(window.location ...

Activating the change event in jQuery: A step-by-step guide

Within my ASP.NET page, I have included a UserControl that contains a RadioButtonList. Whenever an item in the RadioButtonList is changed, I need to trigger the following jQuery function: $('#rdlUser').change(function (e) { alert("change fun ...

Is it possible to place Angular Material components using code?

Currently, I'm in the process of creating a responsive Angular application. Is there any way to adjust the height and position of the <mat-sidenav-content></mat-sidenav-content> component in Angular Material programmatically without relyi ...

Tips on setting and utilizing custom environment variables in a Vue Electron application

What is the best way to integrate custom environment variables into my Electron application? I need to securely store API keys and other sensitive information without hardcoding them directly into the code. My app is built with Vue and Electron. To tackle ...

navigating through an array with a loop (for)

I created a basic phone book program where users can input a name and it will search an array of objects for the corresponding phone number. If the name is found, it will display the name and phone number. However, I am facing an issue where even though ...

What is the best way to retrieve the input value from post.ejs?

app.js var express = require('express'); var bodyParser = require('body-parser'); var app = express(); var passport = require('passport'); var localStrategy = require('passport-local'); var axios = require("axi ...