How can I update information based on the chosen option in a select dropdown using Vue?

I have a chart displayed in my user interface that needs to be updated based on the selected time period. By default, the chart displays data from the past year, but when the user selects "Month," it should show data from the past month.

    <div class="graph">
      <p>Select {{ selected }}</p>
         <form>
           <select class="select" v-model="selected">
             <option value="year">Year</option>
               <option value="month">Month</option>
                 <option value="week">Week</option>
           </select>
         </form>
   <canvas id="mix" count="2"></canvas>
   <chartjs-line target="mix"></chartjs-line>
   <chartjs-bar :labels="mylabels" :datasets="mydatasets" target="mix"></chartjs-bar>
   </div>
export default { 
  data(){
   return{
     mydatasets:[{
                    responsive:true,
                    borderWidth: 2,
                    data: [20, 50, 20, 41, 26, 15, 20, 10, 29, 5, 33, 55] // this data should update based on the selected time period
                }]
         }
        }
      }

Answer №1

In order to display specific data based on the selected value in the drop-down menu

    <form>
       <select class="select" @change="changeHandler" v-model="selected"> // event listener for change
         <option v-bind:key="item" v-for="item in selectArr">{{item}}</option>
       </select>
    </form>
   export default {
      data(){
         selected: 'Year',
         selectArr: ['Year', 'Month', 'Week']
      }
   },
      methods:{
      changeHandler(){
         let selected = this.selected;
         if (selected === 'Month'){
            this.dataChart = [2, 12, 8, 22, 31, 6, 10, 32, 5, 36, 21, 21];
         } else if (selected === 'Week') {
            this.dataChart = [8, 2, 18, 3, 13, 32, 10, 8, 12, 34, 21, 12];
         } else if (selected === 'Year') {
            this.dataChart = [44, 49, 48, 49, 55, 47, 43, 55, 53, 43, 44, 51];
          }
      }
   }

Answer №2

Observing the transformation of the "selected" through the watch property...

<script>
export default { 
  data(){
    return{
      mydatasets:[{
        responsive:true,
        borderWidth: 2,
        data: [20, 50, 20, 41, 26, 15, 20, 10, 29, 5, 33, 55] // this data needs to be updated based on selected value
      }]
    }
  },
  watch: {
    selected: {
      immediate: true,
      handler: function (newValue) {
        switch (newValue) {
          case "Year":
            // update this.mydatasets[0].data with something
            break;
          case "Month":
            // update this.mydatasets[0].data with something
            break;
          case "Day":
            // update this.mydatasets[0].data with something
            break;
        }
      }
    }
  }
}
</script>

Answer №3

To achieve this functionality, you can utilize the PHP switch case along with JavaScript or AJAX. Below is an illustrative example using PHP:

<?php
    $selectedPage = null;
    if(isset($_POST['page'])){
        $selectedPage = $_POST['page'];
    }
    switch($selectedPage){
        case 'page3': include_once('/path/to/some.php'); break;
        case 'page2': include_once('/path/to/some.php'); break;
        case 'page1': include_once('/path/to/some.php'); break;
        default: include_once('/path/to/default.php'); break;
    }
    ?>

<form action="" method="post">
    <select name="page" onchange="window.location=this.value"">
        <option value="page1"<?php if($selectedPage == "page1"){ echo " selected"; }?>>Year</option>
        <option value="page2"<?php if($selectedPage == "page2"){ echo " selected"; }?>>Month</option>
        <option value="page3"<?php if($selectedPage == "page3"){ echo " selected"; }?>>Week</option>
    </select>
</form>

The behavior depends on the option clicked. For instance, selecting "Year" sets $selectedPage to 'page1', which triggers the display of the year-related chart in some.php file.

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

The call stack size has reached its maximum limit due to running 2 Collection.find commands

I've encountered a Maximum call stack size exceeded exception in my Chrome console while working with Angular2 and Meteor. This issue started after I added the following code to my client side: var userChannelsId = UserChannels.find({idUser: Meteor.u ...

Is it possible to utilize Nuxt exclusively as a Single Page Application (SPA)?

My current tech stack includes Angular and Node.js. I have dabbled with Vue on a few simple projects, and recently came across Nuxt3 in some videos. I'm curious to know if Nuxt3 supports single page applications (SPAs) with a Node.js API integration. ...

Reverting back to PDF using jQuery

I am currently utilizing jQuery to send JSON data back to the server, which in turn generates a PDF report. However, I am facing an issue where the PDF is not downloading despite specifying the necessary response header and including JavaScript as shown ...

Implementing a Collapse and Expand All feature within an Accordion Component

Hey there! I've been attempting to implement a Collapse All feature on my accordion but am having trouble figuring it out. The resource I've been referencing is this one. I've searched around and noticed that this accordion setup is a bit d ...

What is the best way to send a 102 Processing status code in Express?

I'm in the process of configuring a new HTTP server to run a lengthy command and return the output of that shell command back to the client. Currently, I am using Express v4.17.1. However, requests from clients are consistently timing out when runnin ...

What is preventing me from accessing the variable?

Having some trouble using a variable from JSON in another function. Can someone lend a hand? async function fetchData() { let response = await fetch('https://run.mocky.io/v3/b9f7261a-3444-4bb7-9706-84b1b521107d'); let data = await response.js ...

Confirmation checkbox that retains original value if canceled

Imagine a scenario where there is a checkbox value. When the checkbox value changes, the user is asked, "Do you want to SHOW this item on the website?" or "Do you want to HIDE this item on the website?" Everything seems to be working fine, except for one ...

Managing server errors when utilizing Observables

i am currently developing an Angular 2 application and part of it includes a login feature that utilizes this service. import { Http, Response } from '@angular/http'; import {Injectable} from '@angular/core'; import 'rxjs/add/op ...

How can I retrieve the value from the input field using vue.js?

I am currently utilizing the vue-js-toggle-button library. While I understand that I can access the value inside the name using $refs, the issue arises as I have 3 toggle buttons and cannot set a Ref because I want to retrieve the name value dynamically i ...

An HTML document may display a segment of a URL

Is there a way to display part of a URL in an HTML document, so that if the URL changes, the corresponding content in the body also updates? For instance, www.example.com/?key=i - Is it possible for this link to be dynamically displayed within the body o ...

The getTotalLength() method in SVG may not provide an accurate size measurement when dealing with non-scaling-stroke. To obtain the correct scale of

In my current project, I am utilizing JavaScript to determine the length of a path and apply half of that length to the stroke-DashArray. However, I have encountered an issue as I am using vector-effect="non-scaling-stroke" in order to maintain a consisten ...

Why styled-components namespace problem in React Rollup build?

I designed a "UI Library" to be utilized in various projects using ReactJS + TypeScript + styled-components and Rollup. However, I am currently encountering issues with conflicting classNames. I am aware that styled-components offers a plugin for creating ...

What is the regular expression that allows numbers between 1 and 24, including decimals?

Can anyone help me create a regex expression that only allows numbers between 1 and 24, with up to 2 decimal places? The numbers should range from 1 to 24, as well as include decimals like 1.00, 1.01, 1.02, all the way up to 24.99. ...

"Utilize the parent component's functionality by extending/inheriting it

export default function PageTemplate() { return ( <div className="layout"> <LeftMenu /> <div className="content"> <TopMenu /> <div id="other-contents"> ...

Retrieve the element that triggered the event listener within Nuxt

I am currently developing a Nuxt project where I have set up my component using the code below. The select-parent-container has a click event attached to it. Whenever this event is triggered, I need to identify and return the specific parent container that ...

Guide on sending information using ajax using a button within a form

I've been working on creating a form that utilizes HTML5 validations and integrates Ajax to show the status of mail sending. However, I'm facing an issue where clicking the send button does not initiate the expected action. Form HTML: <div c ...

How can I extend the date range with JavaScript?

I am working with a variable called {{ $daterange }} that contains JSON data structured like this: { "starts_at": "2020-05-20", "ends_at": "2020-05-23" }, { "starts_at": "2020-05-24", "ends_at": "2020-05-26" }, { "starts_at": "2020-05- ...

Attempting to prevent redundant loading of a component repeatedly

Welcome to the Code Zone Incorporating Laravel 5.8 and Vue.js components for an enhanced user experience. Identifying the Problem Within the code structure, there exist 3 tabs. When Component 1 is selected, it loads successfully. Then when Component 2 i ...

Iterate through a collection of nested objects and check them against an object contained within an array

I'm facing a frustrating issue in Firebase where I am required to compare an object returned to me with an array. I need assistance in completing this method: const removeAlreadySeenUsersFromQueue = (newUsers, likedUsers) => { } The scenario is ...

Unable to display image source in viewport

Currently, I am working on developing a basic ionic app that interacts with an API that I have created. I am encountering an issue where all data is being displayed correctly in the view except for the src attribute of an image. When I use console.log to c ...