Implementing Vue's dynamic component addition feature

I recently came across an interesting article on dynamically adding different components in Vue. The article explains a good method for binding different components to tabs, but I have a specific requirement. I want to bind one type/name component that will vary based on the props passed to it. Additionally, each tab should correspond to a unique instance of the component with the corresponding props. Is there a way to reuse my component across different tabs?

For example:

<template>
  <button
          v-for="tab in tabs"
          v-bind:key="tab.name"
          v-bind:class="['tab-button', { active: currentTab === tab }]"
          v-on:click="currentTab = tab"
  >
        {{ tab.name }}
  </button>
  <component v-bind:is="currentTab.component" :id_1=currentTab.id_1 :id_2=currentTab.id_2></component>
</template>

<script>
import tab-component from "..."
var tabs = [
  {
    name: "WS1",
    component: "tab-component",
    uwb_id: "PL_DL_test",
    ws_id: "id_Ws_1"
  },
  {
    name: "WS2",
    component: "tab-component",
    uwb_id: "PL_DL_test",
    ws_id: "id_Ws_2"
  }
]

export default {
  components: {
    tab-component
  },
  data() {
    return {
      tabs: tabs,
      currentTab: tabs[0],
    }
  }

}

<script>

Is there a way to achieve this level of flexibility and reusability within Vue components?

I appreciate any insights or suggestions on how to accomplish this!

Answer №1

To achieve this, you can utilize the computed property.

<template>
  <button
    v-for="(tab, index) in tabs"
    :key="tab.name"
    :class="['tab-button', { active: currentTabIndex === index }]"
    @click="currentTabIndex = index"
  >
    {{ tab.name }}
  </button>
  <component :is="activeTab.component" :prop1="activeTab.prop1 :prop2="activeTab.prop2"></component>
</template>


export default {
  components: {
    tab-component
  },
  data() {
    return {
      tabs: [
        {
          name: "WS1",
          component: "tab-component",
          uwb_id: "PL_DL_test",
          ws_id: "id_Ws_1"
        },
        {
          name: "WS2",
          component: "tab-component",
          uwb_id: "PL_DL_test",
          ws_id: "id_Ws_2"
        }
      ],
      currentTabIndex: 1
    }
  },
  computed: {
    activeTab () {
      return this.tabs[this.currentTabIndex]
    }
  }

}

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

Is it possible to generate a Token in Nexus for private packages without using the UI interface?

We have implemented Sonatype Nexus Repository ManagerOSS 3.29.0-02 and are currently facing an issue in generating a TOKEN that can be used with .npmrc following this specific structure: registry=http://NEXUS-IP:8081/repository/GROUP-NAME http://NEXUS-IP:8 ...

Adding a character at the beginning of each loop iteration in a nested array with Vue.js

When working inside a v-for loop, I am attempting to add a character at the beginning of each item in a nested array that may contain multiple items. I have explored various options but have not been successful: :data-filter="addDot(item.buttonFilter ...

Preventing the default behavior using event.preventDefault() does not seem to be effective when submitting a

Why is the event.preventDefault() method not functioning properly? <script type="text/javascript" src="vue.js"></script> <div id="app"> <form v-on:submit.prevent="saveData"> <input type="text" name="test"> <button ...

What is the best way to detect component errors on the server with Angular Universal?

Here is a snippet of my server code that renders the Angular home.component: app.get("*", (req, res) => { res.render( `../${CLIENT_DIST_DIR}/index`, { req: req, res: res, providers: [ ...

Passing data between files in VUE3

Extracting data from db.json in the Home.vue component and storing it in the jobs: [] array is a common practice. export default { name: 'Home', data() { return { jobs: [], } }, components: { }, mounted() { fetc ...

Put Jest to the test by testing the appendFileSync function

I am currently working on creating a test for appendfilesync function. When using a logger, I noticed that one line of code is not covered in my tests. Below is the code snippet I am referring to (please note that I am using tslog for logging purposes): ex ...

Save the value of a promise in a variable for future use in state management within a React-Native application

let storage = AsyncStorage.getItem('@location_data').then(data => data) const MainApp = () => { let [currentLocation, setCurrentLocation] = useState(storage); The current situation is that the storage variable holds a promise. How can ...

What is the technique for utilizing JavaScript to toggle the opening and closing of a Bootstrap 5 navbar dropdown?

My website is built using Bootstrap 5, and I am working on creating a navbar dropdown functionality. On desktop, I want the dropdown to open on hover and lead to a new page when clicked. However, on mobile, I only want the dropdown to open and close on cli ...

Discovering whether the incoming request to an AngularJS application is a GET or POST request can be efficiently accomplished

I recently started learning angularjs and I successfully built an application using the angular seed skeleton https://github.com/angular/angular-seed for the client side. For my API server, I utilized expressjs server. The URL of my home page is localhost ...

Tips for extracting header ID from the HTML/DOM using react and typescript

I developed a unique app that utilizes marked.js to convert markdown files into HTML and then showcases the converted content on a webpage. In the following code snippet, I go through text nodes to extract all raw text values that are displayed and store t ...

What is the best way to send a parameter to the callback function of a jQuery ajax request?

I am facing an issue where I need to pass additional variables to a jQuery ajax callback function. Consider the following scenario: while (K--) { $.get ( "BaseURL" + K, function (zData, K) {ProcessData (zData, K); } ); } func ...

Utilizing ng-href in Angular.js Template: A Guide

I am attempting to develop a simple Single Page Application (SPA) with just one index.html file that includes templates. However, I encountered an issue with the ng-href directive: <a ng-href="#/myPage">myPage</a> This works fine in index.h ...

Discovering how to navigate to a link within a web table using Cypress has been a challenge, as I keep receiving the error message stating that the element is not visible due to its CSS property being

Trying to click on the first enabled link in the 'Action' column of a web table has been proving difficult. In the example given, the first two rows do not have an enabled link, so the goal is to click on '8.5 AccountH' https://i.stack ...

What are some ways to include additional data besides the new value in a change event for an input field?

Currently, I am using VueJS to dynamically generate a form based on a JSON schema and then attempting to save the data into my Vuex state. Here is an overview of the code I have written so far (simplified): <div v-for="field in schema" :key=& ...

`Zooming and scrolling feature within a masked image`

I'm struggling to achieve a scrolling zoom effect similar to the website mentioned below, but I can't seem to get it to fully zoom. Additionally, when I try to zoom in on a clipped shape or text while scrolling, the entire div ends up scrolling ...

I am having trouble comprehending this JavaScript code, could someone provide me with assistance?

Currently delving into the world of JavaScript functions and stumbled upon this code snippet with the following output: Output: "buy 3 bottles of milk" "Hello master, here is your 0 change" function getMilk(money, costPerBottle) { ...

What could be causing the if/else block in my Redux Toolkit reducer to malfunction?

I'm currently working on a shopping cart feature where I need to increase the quantity of an item if it's already in the cart. If the same item with different sizes is added, they should be displayed separately. I've successfully implemented ...

The most effective method for positioning a child element to the left and top using Flexbox grid

I am currently working on visualizing queues and processes within a system. Each process is associated with a specific queue from which it retrieves data. I aim to create a layout similar to the following: https://i.stack.imgur.com/BXyts.png However, I a ...

Crop and upload images asynchronously using Node.js

I need to resize an image into multiple sizes and then upload them to AWS S3. The specific resizing dimensions are stored in an array. To accomplish this, I am utilizing the async waterfall method along with the series method. async.each(crop_sizes, func ...

Focus on targeting each individual DIV specifically

Is there a way to toggle a specific div when its title is clicked? I have tried the following code snippet: $( '.industrial-product' ).find('.show-features').click(function() { $('.industrial-product').find('.ip-feat ...