Designing a webpage with a form and incorporating a dynamic Google graph visualizer using VueJS

Hello VueJS enthusiasts! I'm diving into VueJS and seeking guidance on structuring my code efficiently.

My current project involves creating a dynamic Google chart that updates based on user selections from two radio inputs - "House" or "Apartment", along with an input field for entering a postal code.

I have implemented a component to display the Google graph, and I understand that passing a prop argument to personalize it is essential.

Take a look at my HTML code snippet:

<div id="graph_app">
  <input id="apartment" @click="updateData('49099')" type="radio" name="housing" value="apartment" v-model="picked"> Apartment 
 <input id="house" type="radio" name="housing" value="house" v-model="picked"> House

 <input type="text" placeholder="Enter a city name in France" v-model="query" @keyup="getData()" @click="reset()" autocomplete="off" class="form-control input-lg" />
  <div class="panel-footer" v-if="search_data.length">
      <ul class="list-group">
        <li>
         <a href="#" class="list-group-item" v-for="data1 in search_data" @click="getName(data1)">{{ data1.commune }}</a>
        </li>
      </ul>
    </div>
    <graph :data="chartData"></graph>
</div>

Here is the corresponding JavaScript code:

<script>
  
Vue.component('graph', {
  delimiters: ['${', '}'],
  template: '<GChart type="LineChart" :data="chartData" :options="chartOptions"/>',
  props: ["data2", "options"],
  data:function(){ 
    return {
      chartData: [
        ['Year', 'Price'],
        ['2016', 50],
        ['2017', 100],
        ['2018', 200],
        ['2019', 100],
        ['2020', 150]
      ],
      chartOptions: {
        chart: {
          title: 'Median Housing Prices for this City',
          subtitle: 'Price by year 2016-2021',
          
        },
        curveType: 'function',
        height: 500,
        pointSize: 10,
      }
    }
  },
  computed: {
    chartData: function() {
      return this.chartData;
    }
  },
  watch: {
      chartData: function() {
        this._chart.destroy();
        this.renderLineChart();
        console.log("Graph updated");
        }
    },
  methods: {
  }
});

var app = new Vue({
    el:'#graph_app',
    data: {
      picked:'',
      query:'',
      search_data:[],
      chartData:[],
    },
    methods:{
      getData:function(){
        this.search_data = [];
        axios.post('fetch.php', {
          query:this.query
        }).then(response => {
          this.search_data = response.data;
        });
      },
      getName:function(data){
        this.query = data.commune;
        this.search_data = [];
        this.updateData(data.code_commune);
      },
      reset:function(){
        this.query = '';
      },
      updateData(code) {
        console.log('city_code='+code);
        axios.post('fetch_graph.php', {
          city_code:code
        }).then(response => {
            var res = response.data;
            var result = [['Year', 'Price']];
            var i = 0;
            for(var line in res)
            {
                i++;
                Vue.set(this.chartData, i, [res[line].year, parseInt(res[line].median)]);
            }
        });
    }
    }
});

</script>

I'm grappling with understanding components, props, v-bind/v-model attributes... Can anyone suggest a more structured approach for my task? Any help is greatly appreciated!

Thank you in advance!

Answer №1

It is recommended to create a prop called "data" in your component called "graphique" to receive external data. You can then assign the value of this prop to an object defined in the data section of the component. Use a watcher to detect any future updates to the data.

Additional code has been omitted for brevity.

Vue.component('graphique', {
template: `
    <GChart type="LineChart" :data="chartData" :options="chartOptions"/>
`,
props: ['data'],
data() {
   return {
     chartData: null
   }
},

watch: {
   data: {
     immediate: true,
     handler(newValue) { this.chartData = newValue}
   }
}
});

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

Top method for transferring the result of a function to descendant components in Vue

In my parent component, I have a data object named config structured like this: data() { return { config: { Groups: [ { name: "A", Types: [ { mask: 1234, name: ...

Clicking on Bootstrap Select Does Not Trigger Dropdown Opening

Currently, I am working on generating a dynamic set of bootstrap-select widgets that include a dropdown. My main challenge lies in preventing the select from closing the dropdown, which requires me to use 'event.stopPropagation()' on the dropdown ...

What is the best way to determine the height of a DIV element set to "auto"?

When setting a fixed height on a div using jQuery, such as $('div').height(200);, the value of $('div').height() will always be 200. This remains true even if the content within the div exceeds that height and overflow is hidden. Is th ...

Execute the knockout function using jQuery

There's a scenario where I am trying to trigger a knockout method using jQuery. The Knockout viewModel has already been bound, but I'm unsure of how to call it using jQuery. Below is the snippet of my code: $(document).ready() { form_submit( ...

Using a function as a parameter in a React component constructor

I have a question about a snake game I'm developing using React. After reading a post on Stack Overflow discussing setting functions inside the constructor, I am facing an issue with calling a function (foodGenerator) from within another function (sn ...

I am experiencing an issue where my JSON array is only returning the last element. Any suggestions on how to

I am facing an issue with my JSON array and Ajax code. Here is the snippet of my code where I upload an Excel file, convert it to JSON, then save it as a string in my database: function exportExcelToTable() { $('#upload-excel-convert').chang ...

Skip nodes in Polymer 1.0 by using ExcludeLocalNames

I recently attempted to transition from Polymer version 0.5 to 1.0 and came across a particular question: Is there a way to exclude certain nodes inside a paper-menu? In the previous version (0.5), you could use the attribute excludedLocalNames to achieve ...

Do individual JavaScript script tags operate independently of one another in terms of error handling?

My main goal is to establish a connection to my server using websockets and send messages to the browser for remote page reloads. I want to ensure that this code runs independently of any other errors on the page, allowing me to remotely refresh the page i ...

Dealing with the issue of incompatible types in TypeScript with Vue 3 and Vuetify: How to handle numbers that are not assignable to type Readonly<any

Currently, I am utilizing Vite 3 along with Vue 3 and Vuetify 3 (including the Volar extension and ESLint). Additionally, I am incorporating the composition API in script setup mode. Within my HTML code, I am utilizing Vuetify's v-select. Unfortunate ...

Retrieve characteristics from removed or replicated entities and allocate them to different entities

Looking for a bit of assistance with an array transformation: [ {Code:13938, Country:699, Name:"Crocs", codeProduct:1} {Code:13952, Country:699, Name:"Polo Club", codeProduct:14} {Code:13952, Country:699, Name:"Polo Club", codeProduct:1} {Code ...

Utilizing jQuery to apply multiple classes simultaneously?

What is the purpose of allowing multiple classes to be added? Is there any real benefit to this feature or is it just unnecessary complexity? I attempted to utilize it, but found that it serves no practical function. ...

Looking to incorporate React Canary in raw HTML? Or perhaps interested in adding react-dom/client into your project?

Due to certain undisclosed reasons, I am developing a React application without the use of bundlers like webpack. Instead, I simply include React and ReactDOM using <script> tags in my index.html, fetching them from a CDN: https://cdnjs.cloudflare.co ...

Unable to integrate Express.js into my React JS project

Having trouble integrating express.js into my react js Project. After adding the following lines to my app.js code: const express = require('express') const app = express(); I encounter the error messages below: - Module not found: Error: Can&ap ...

Establishing express routing results in API call returning 404 error indicating resource not found

I need some clarification on how to configure my Express routing using app.use and router. My understanding is that I can create a router and then attach it to a route using app.use() to handle all routing related to that route. Can someone assist me in ...

Having trouble with jQuery animate function?

I have been struggling to get my animate function to work, despite looking at multiple similar posts and making modifications to my code. My goal is to make an image of a plane move from left to right across the screen and stop halfway. Here is the code I ...

Top method for identifying "abandoned words" within text that has been wrapped

Our content and design teams have a specific request to prevent paragraphs from ending with an "orphan word" - a single word on the last line of text that has wrapped onto multiple lines. The designer's proposed solution is to adjust the margins sligh ...

How can you retrieve the chosen option's value in select2 and subsequently assign it to an input text using jquery?

I am a beginner in the world of jQuery and JavaScript, so please forgive me if this is a basic question. I am currently encountering an issue where I am unable to set the value obtained from a selected option in select2 to a text input field. Here's m ...

What's the reason for not being able to customize classes for a disabled element in Material-UI?

Currently, I am utilizing Material-UI to style my components. However, I am facing challenges when trying to customize the label class for disabled buttons. Despite setting a reference as "&$disabled", it does not yield the desired results. import Rea ...

The event listener for 'annotations.create' in the PSPDFKIT instance does not include the required annotation type

I'm facing difficulties with integrating pspdfkit to properly create and display my annotations. My goal is to create annotations in the following manner: instance.addEventListener("annotations.create", createdAnnotations => { ...

Issue with Intel XDK: the document.location.href is directing to an incorrect page

Hello Community of Developers, I have been experimenting with different methods but still haven't found a solution. In my project using Intel XDK, whenever I attempt to change the page using location.location.href = "#EndGame" or similar codes in Java ...