Ways to transfer chosen key to a different template

Is there a way to transfer a selected key to another template for displaying a chart? I've developed a template that exports a multi-line chart, utilizing Axios to retrieve data from an API.

In the home page, there's a dropdown menu. When a user selects an item, the chosen item or its value should be passed to the chart template so that it can return a chart for that selected item.

// Home component
<template>
  <section>
    <label>City</label>
    <select @change="getArea()" v-model="key" class="custSelect2">
      <option :value="0">Select City</option>
      <option v-for="data in cityList" :value="data.id">{{ data.city }}</option>
    </select>

    <label>Area</label>

    <select @change="getWard()" v-model="keyArea" class="custSelect2">
      <option :value="0">Select Area</option>
      <option v-for="data in areaList" :value="data.id">{{ data.area}}</option>
    </select>

    <label>Ward</label>
    <select v-model="Polekey" @change="getPole()" class="custSelect2">
      <option :value="0">Select Ward</option>
      <option v-for="data in wardList" :value="data.id">{{ data.ward}}</option>
    </select>
    <label>Pole</label>
    <select v-model="PoleSelected" class="custSelect2">
      <option :value="0">Select Pole</option>
      <option v-for="data in PoleList" :value="data.poleid">{{ data.poleid}}</option>
    </select>
    <div>
      <Areachart />
    </div>
  </section>
</template>
// Area component
<script>
import { Line } from "vue-chartjs";

export default {
  extends: Line,
  data() {
    return {
      dataList: []
    };
  },
  mounted() {
    var self = this;

    axios
      .get("http://172.31.0.114:5008/api/city/data" + this.key) // key is the value that user selected
      .then(function(res) {
        self.dataList = res.data;
        // how to initilize data into below datasets
      })
      .catch(function(error) {
        console.log("Error:", error);
      });

    this.renderChart(
      {
        labels: [],
        datasets: [
          {
            label: "Data One",
            borderColor: "#FC2525",
            backgroundColor: this.gradient,
            data: []
          },
          {
            label: "Data Two",
            borderColor: "#05CBE1",
            data: []
          }
        ]
      },
      { responsive: true, maintainAspectRatio: false }
    );
  }
};
</script>

Answer №1

  1. Ensure that _key is passed as a prop to the child component (assuming it's a required String);
  2. Set up a watcher for changes in _key and trigger the updateChart method accordingly, making API calls as needed;
  3. Create an updateChart method to handle GET requests, process data, and update the chart display;
  4. Invoke the updateChart method within the mounted lifecycle hook to load initial data;
  5. Define the datasets array in the data section so it can be modified based on server responses;
  6. Remember to pass the _key prop from the parent component to the child component.
// In ParentComponent
<template>
  <Areachart :_key="PoleSelected"/>
</template>

<script>
import { Line } from "vue-chartjs";

export default {
  extends: Line,
  props: {
    _key: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      datasets: [
        {
          label: "Data One",
          borderColor: "#FC2525",
          data: []
        },
        {
          label: "Data Two",
          borderColor: "#05CBE1",
          data: []
        }
      ]
    };
  },
  watch: {
    _key() {
      this.updateChart();
    }
  },
  mounted() {
    this.updateChart();
  },
  methods: {
    updateChart() {
      axios
        .get("http://172.31.0.114:5008/api/city/data" + this._key)
        .then(res => {
          // proccess the response
          // I don't know your data model, so i can't write appropriate handler
          // for example this.datasets[0].data = res.data[0]

          this.renderChart(
            {
              labels: [],
              datasets: this.datasets
            },
            { responsive: true, maintainAspectRatio: false }
          );
        })
        .catch(function(error) {
          console.log("Error:", error);
        });
    }
  }
};
</script>

Answer №2

If you want to transfer data to a component using props, you can use the following syntax:

<Areachart :data="values"/>

Another way to send data is by creating an event bus. You can utilize $emit method to transmit the event and $on method to receive it.

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 is the process for obtaining a value when you click and then retrieving the associated ID?

I am looking to create a function that, when clicking on the square with the ID "colors", will return the sentence containing the colors from the table in PHP files with the ID "retours_couleurs". Apologies for any mistakes in my English, as I am French. ...

What is the best way to trigger the jQuery-File-Upload event within this function?

Before uploading a file, I want to check the API first. $('.file_upload_button_wrapper').on('click', function () { // perform check here $.ajax({ url: '/?app=files&getfile=ajax%2Fupload.php', ...

Refresh a specific DIV element without having to refresh the entire page

I have a Div Tag that includes Small.php to populate it with information. My goal is to refresh the content every 15 seconds without reloading the entire webpage. I've attempted using JavaScript/jQuery without success. <script type="text/javascrip ...

What are some ways to enhance the opacity of a Material UI backdrop?

I'm looking to enhance the darkness of the material UI backdrop as its default appearance is not very dark. My goal is to make it dimmer and closer to black in color. ...

Displaying divs depending on dropdown selection - Troubleshooting script issue

When I try to display certain divs based on dropdown selection using the script below, it works fine on a simple page. However, when I implement it on my current development page, it completely messes up the layout, turning everything black and adding stra ...

Issue with loading Babel preset in a monorepo setup

I'm working with a monorepo setup using Lerna and it's structured as follows: monorepo |-- server |-- package1 |-- package2 All packages in the repo make use of Babel. After installing all 3 projects, yarn copied all the required @babe ...

An error was encountered while trying to use the 'export' token in lodash-es that was not

Transitioning from lodash to lodash-es in my TypeScript project has been a challenge. After installing lodash-es and @types/lodash-es, I encountered an error when compiling my project using webpack: C:\..\node_modules\lodash-es\lodash. ...

A Guide to Connecting a JavaScript File to an HTML Page with Express and Node.js

Struggling with integrating my JavaScript file into my simple NodeJS app. Traditional methods like placing the script in the header doesn't seem to work with Node. I've attempted using sendFile and other approaches, but none have been successful ...

Explore one of the elements within a tuple

Can we simplify mapping a tuple element in TypeScript? I'm seeking an elegant way to abstract the following task const arr: [string, string][] = [['a', 'b'], ['c', 'd'], ['e', 'f']] const f ...

Exploring the ability to join multiple voice connections simultaneously with Discordie

Is there a way to establish multiple voice connections for a bot using Discordie without disconnecting from the previous connection? If so, how can this be achieved? Here is my code: const Discordie = require("discordie"); const fs = require('fs&a ...

Displaying the quantity of directories within a specific location

Can anyone help me troubleshoot my code? I'm trying to have a message displayed in the console when the bot is activated, showing the number of servers it is currently in. const serversFolders = readdirSync(dirServers) const serversCount = parseInt(s ...

Exploring Recursive Types in TypeScript

I'm looking to define a type that can hold either a string or an object containing a string or another object... To achieve this, I came up with the following type definition: type TranslationObject = { [key: string]: string | TranslationObject }; H ...

Content formatted with a gap

I wish to include a gap between each sample usage with markdown. For instance: .kick Sarah, .kick John, .kick Mary .setDescription(`**Usage :** \`${settings.prefix}${command.help.name} ${command.help.usage}\`\n**Example :** \`${setting ...

Why doesn't express.js throw an error when the variable 'app' is used within its own definition?

When working with express.js, I find it puzzling that createApplication() does not throw an error. This is because it uses app.handle(...) within an anonymous function that defines the same variable 'app'. I attempted to replicate this in jsFidd ...

Tips for choosing between options in JavaScript and AngularJS

How can I choose the appropriate <select> tag option using JavaScript or AngularJS in the backend? Hint: I receive data from an API service and populate a form for editing. Assuming the gender is currently set as Male in the database, how can I disp ...

Aggregate the properties of objects in an array into a single object using Lodash

I've been struggling to figure this out on my own, so I decided to seek advice from those with more experience. I have an array of objects called items, and I need to sum up specific properties across different objects in the array. The user can selec ...

The Ajax script triggers the PHP script twice

Utilizing AJAX on my HTML page, I am able to dynamically load data from a MySQL database without reloading the page and send email notifications upon certain events. The process involves Ajax calls to script.php which then makes requests to the database an ...

What could be the reason behind the malfunction of the sideNav function in bootstrap?

I am trying to implement a Bootstrap navbar, but it's not displaying correctly. I keep getting an error in my console that says: https://i.sstatic.net/UwbAS.png I've rearranged the order of my scripts in the head section, but I still can't ...

Tips for Retrieving Data from a Multi-Dimensional Array

I need help accessing the values in my array and assigning them to variables for later use. I have created an array and used the randomGo() function to generate a random number that corresponds to a pair of numbers within the array. My goal is to assign ...

Discovering the width of desktop and mobile browsers to ensure maximum compatibility

While working on media queries, I encountered this code: //Checking various widths as different browsers report them differently if ($(window).width()!==0) { width = $(window).width(); } else if (window.innerWidth!==0) { width = window.inner ...