What is the best way to switch between components in vue.js?

I have created a Dashboard.vue component consisting of two child components: DisplayBooks.vue and sortBooksLowtoHigh.vue. Initially, the sortBooksLowToHigh component is hidden while the displayBooks component is visible by default. The requirement is that when the user clicks on the option to sort books by price Low to High, the DisplayBooks component should be hidden and the sortBooksLowtoHigh component should become visible. Can someone please assist me in resolving this issue?

Dashboard.vue

<template>
<div class="main">
    <div class="navbar navbar-default navbar-fixed-top">
        <div class="navbar-header">
            <img src="../assets/education.png" alt="notFound" class="education-image" />
        </div>
        <ul class="nav navbar-nav">
            <li>
                <p class="brand">Bookstore</p>
            </li>
        </ul>
        <div class="input-group">
            <i class="fas fa-search"></i>
            <div class="form-outline">
                <input type="search" class="form-control" placeholder='search...' />
            </div>
        </div>

        <ul class="nav navbar-nav navbar-right" id="right-bar">
            <li><a> <i class="far fa-user"></i></a></li>
            <p class="profile-content">profile</p>
            <li><a><i class="fas fa-cart-plus"></i></a></li>
            <p class="cart-content">cart</p>
        </ul>
    </div>
    <div class="mid-body">
        <h6 >Books<span   class="items">(128items)</span></h6>
        
        <select  class="options" @change="applyOption">
            <option disabled value="">Sort by relevance</option>
             <option value="HighToLow">price:High to Low</option>
            <option value="LowToHigh">price:Low to High</option>
        </select>
        
    </div>
 <DisplayBooks v-show="flag" />
<sortBooksLowtoHigh v-show="!flag" />
<sortBooksHightoLow v-show="!flag" />
</div>
</template>

<script>
import sortBooksLowtoHigh from './sortBooksLowtoHigh.vue'
import sortBooksHightoLow from './sortBooksHightoLow.vue'
import DisplayBooks from './DisplayBooks.vue'
export default {
    components: {
        DisplayBooks,sortBooksLowtoHigh,sortBooksHightoLow      
    },
    data() {
        return {
           flag:true,
            brand:'Bookstore',
        }
    },
    methods:{
        flip() {
            this.flag = !this.flag;
        },
        applyOption(evt) {
            if(evt.target.value === 'HightoLow') this.flag = true;
            if(evt.target.value==='LowtoHigh') this.flag=true;
            else this.flag = false;
        },
    }

}
</script>

<style lang="scss" scoped>
    @import "@/styles/Dashboard.scss";
</style>


Answer №1

Display "DisplayBooks" when the flag is true and show "sortBooksLowtoHigh" when it's false.

 <select class="options" @change="applyOption">
            <option disabled value="">Sort by relevance</option>
            <option value="HighToLow">price:High to Low</option>
            <option value="LowToHigh">price:Low to High</option>
 </select>

and

<DisplayBooks v-show="flag" />
<sortBooksLowtoHigh v-show="!flag" /> 

and then in

data() {
        return {
            flag:true,
            brand:'Bookstore',
        }
    },
methods:{
        applyOption(evt) {
            if(evt.target.value === "HightoLow") this.flag = true;
            else this.flag = false;
        },
    }

Note that it's methods, not method

Edit:

If you are importing a new component called "sortBookHightoLow.vue," you can set a text value to the flag instead of a boolean value based on your requirement.

 <select class="options" @change="applyOption">
            <option disabled value="">Sort by relevance</option>
            <option value="HighToLow">price:High to Low</option>
            <option value="LowToHigh">price:Low to High</option>
 </select>

and

<DisplayBooks v-show="flag==='noOrder'" />
<sortBooksLowtoHigh v-show="flag==='lowToHigh'" /> 
<sortBooksHightoLow v-show="flag==='highToLow'" /> 

and then in

data() {
        return {
            flag:'noOrder',
            brand:'Bookstore',
        }
    },
methods:{
        applyOption(evt) {
            if(evt.target.value === "HightoLow") this.flag = 'highToLow';
            else this.flag ='lowToHigh';
        },
    }

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

What are the steps for skipping, sorting, and limiting with dynamoose?

After being familiar with MongoDB and mongoose, I am now exploring dynamoose for my app. In order to replicate the below-shown mongoose query using dynamoose, how can I write it? Specifically, I want to achieve the same functionality as the following mong ...

Set the DIV element to match the height of its container

I'm currently using this HTML code, and it's functioning correctly. However, I would like the height of the div to adjust dynamically based on the tab's content, rather than specifying a fixed height of 200px. Using a percentage value for th ...

Enhance Your Three.js Experience: Implementing Dots on Vertices

I am working with a wireframe sphere and looking to add dots to the vertices. Something similar to this image: https://i.sstatic.net/pzNO8.jpg. Below is all of my JavaScript code: var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera( ...

The initial JavaScript load shared by all users is quite large in the next.js framework

Currently working on a project using the Next.js framework and facing an issue where the First Load JS shared by all pages is quite heavy. I am looking for advice on possible strategies to reduce the weight of the JS file, and also wondering if there ...

When trying to manually trigger the firing of the autocomplete function to get a place using Google API

My goal is to retrieve the data from autocomplete.getPlace() when triggering this event manually. Essentially, I have a function that captures the user's location in Lat/Lng format, and afterward, I aim to access other useful data using getPlace() su ...

Error encountered while executing a join query in Node.js

My stack includes express.js, sequelize, and mysql Database Structure A : { id: 1, name: ... } B : { A_id: 1, name: name1 }, { A_id: 1, name: name2 } A Model (models/A.js) A.association = models => { A.hasMany(models.B, { foreignKey: 'A_id&ap ...

Using a template element for looping over an array with conditional rendering

I'm facing a challenge with conditionally rendering elements in a list using Petite-Vue. When I try to place a <li> tag with a v-if attribute inside a <template> tag with a v-for attribute, an error is generated: Uncaught (in promise) Ty ...

Attempting to create a JavaScript function that will show a JSON array when the next button is clicked

I am facing an issue with displaying a JSON array based on specific start and end indices. Even though I managed to display the entire array, the first button click does not seem to work as expected. Upon clicking the first button, an error message "this.d ...

Vuejs Countdown Timer Powered by Moment.js

Currently, I am working on a vuejs page and I am looking to incorporate a countdown timer that counts down from 5 minutes (e.g. 5:00, 4:59, and so on). Although I have never used momentjs before, I have gone through the moment docs but I am finding it ch ...

Tips for converting file byte code to file form data

From one folder I am retrieving a file and uploading it to another server. However, when I extract the file from the first folder, I receive a byte code representation of that file. The API for uploading the file to the second folder requires FormData as a ...

Is it necessary to integrate the Facebook JavaScript SDK even if I do not plan on utilizing its features?

I have created some simple applications to use as custom tabs on my Facebook page, consisting of hyperlink images. I am not utilizing any of the functionality provided by the Facebook JavaScript SDK in these instances. Do I really need to load the Faceboo ...

ways to make a list element inaccessible by using either Javascript or jQuery

When the user clicks on my eraser, I want the color to be hidden or not display its dropdown elements. I attempted this with the following code snippet. $('#chooseEraser').mousedown(function(e){ curTool = "eraser"; checkEraser ...

Trigger an alert message upon clicking a button within CK Editor

Is it possible to trigger an alert message using ckeditor when a specific button is clicked? Below is the code snippet for reference: $(document).ready(function () { $(".cke_button__bold").click(function () { editor.on("CKEDITOR.cke_butto ...

Slider MIA - Where Did it Go?

I'm having an issue with my slider. When I load the page, it doesn't show the first image until I click the button to load it. How can I make it display the first image by default? Below is my JavaScript code: <script> var slideIndex = 1 ...

How can I adjust the font size of material-ui buttons while ensuring that they scale appropriately?

Having trouble adjusting the font sizes on Material-UI's RaisedButton for React and ensuring that the button scales properly along with it. <RaisedButton label={<span className="buttonText">Log in Here</span>} /> CSS: .buttonText ...

Alter the button's color seamlessly while staying on the same page

I have implemented a feature that allows me to change the category of photos without having to leave the page and it works perfectly. My next goal is to create a button system where the pre-defined category of a photo is indicated by a button with a green ...

Exploring the capabilities of SVG and audio integration in web browsers

I am curious if it's possible to incorporate audio into an SVG file in a web browser. I came across this thread here, but unfortunately, I can't leave a comment =/ I tried implementing the code from this website, but it doesn't seem to work ...

Invoking a Typescript function from the Highcharts load event

Struggling to call the TypeScript function openDialog() from the events.load of Highcharts? Despite using arrow functions, you are running into issues. Take a look at the code snippet below: events: { load: () => { var chart : any = this; ...

Discovering the number of words, extracting specific words, and transferring them to a URL using JavaScript

I have retrieved a document from a URL and saved the response. There are 3 tasks I need to accomplish here:- Calculate the word count in the document. Gather information for the top 3 words (sorted by frequency) including synonyms and parts of speech. A ...

When attempting to make a post using Prisma's ORM, users may encounter an error message indicating that the post function

Creating a basic prisma application using express and node to query a local mysql database. Encountering an error when calling await prisa.list.create(), details provided below. Here is the script.js code snippet from the HTML page: addItemForm.addEvent ...