component load based on category value change in vuejs

 To load a different component based on a change in category value in Vue.js, you can use the computed property to return the appropriate component based on the selected category value.

Here's an example code snippet:

<template> <div> <select v-model="selectedCategory"> <option v-for="category in categories" :key="category" :value="category"> {{ category }} </option> </select> <component :is="currentComponent"></component> </div> </template> <script> import Component1 from './Component1.vue'; import Component2 from './Component2.vue'; import Component3 from './Component3.vue'; export default { components: { Component1, Component2, Component3, }, data() { return { selectedCategory: 'Category 1', categories: ['Category 1', 'Category 2', 'Category 3'], }; }, computed: { currentComponent() { if (this.selectedCategory === 'Category 1') { return 'component1'; } else if (this.selectedCategory === 'Category 2') { return 'component2'; } else if (this.selectedCategory === 'Category 3') { return 'component3'; } else { return 'component1'; } }, }, }; </script>

In this example, we have a select element that allows the user to choose a category. We use v-for to loop through the categories array and display each category as an option in the select element.

We use the component element to dynamically display the current component based on the selected category value. We use the :is attribute to bind the component to the currentComponent computed property.

We import the components (Component1, Component2, and Component3) at the top of our Vue component and register them as local components using the components option.

We use the computed property to return the appropriate component based on the selected category value. We use an if-else statement to check the value of the selectedCategory property and return the appropriate component name as a string.

Note that you can also use the watch option to monitor changes to the selectedCategory property and perform some actions based on the new value. However, using a computed property is generally a cleaner and more efficient way to dynamically display components based on a data property.



EmoticonEmoticon