Why am I unable to utilize methods in Vue.js?

Hey everyone, I'm currently working on a website that includes a home page and a specific 'Brazil' component. To switch between the two, I am using vue router. Within the Brazil component, there is a calculator feature that should take a grade input from the user and calculate the average once they click on the 'Average' button. While the calculation itself seems to be correct, the buttons are not functioning as expected. Does anyone have any insight into what might be causing this issue? Here's a snippet of the code in question:

<template>
  <div>
    Brazil
    <h2>Grade-Calculator </h2>
    <div id="calculator">
      <ul>
        <li v-for="(g,idx) in grades" :key="idx">{{idx+1}}. Grade : {{g}}</li>
      </ul>
      <div>
        <label>New Grade: </label>
        <input type="text" v-model="newGrade" />
        <button v-on:click="addGrade()">Ok</button>
      </div>
      <br>
      <div>
        <button v-on:click="calcAvg()">Average</button>
        <p>Average: {{ sum }}</p>
      </div>
  </div>
  </div>
</template>

<script>
import Vue from 'vue'
export default {
  name: "Brazil",
  props: {}
};
new Vue({
    el: '#calculator',
    data: {
      grades: [],
      newGrade: 0,
      avg: 0
      //TEST
    },
    methods: {
      addGrade: function () {
        this.grades.push(this.newGrade)
        this.newGrade = 0
      },
      calcAvg: function () {
        let sum = 0;
        for (var i = 0; i < this.grades.length; i++) {
          let zahl = parseInt(this.grades[i]);
          sum = sum + zahl;
        }
        //calculate average and print it
        console.log(sum)
        console.log(this.grades.length)
        return sum / this.grades.length;
      }
    }
  })
</script>

Answer №1

Attempting to utilize two different patterns simultaneously on the same component can lead to complications! One involves SFC (single file component), while the other entails rendering a new Vue instance that replaces a specific element within your current DOM.

Based on your description, it appears you are exporting a basic object with minimal properties (such as a name and empty props). Subsequently, you initiate a new Vue instance within the exported SFC. Although this setup may function with sufficient tweaking, it introduces unnecessary complexity.

I made some additional minor corrections:

  • Replaced the average function
  • Removed the sum method referenced but not implemented
  • Adjusted type casting by utilizing Number() instead of parseInt in JavaScript
  • Made a few more unspecified tweaks

To illustrate how your component would be used with Vue.component() declaration:

Vue.config.productionTip = false;
Vue.config.devtools = false;
Vue.component('Calculator', {
  template: `
    <div>
      <h2>Grade-Calculator</h2>
      <div>
        <ul>
          <li v-for="(g,key) in grades" :key="key">{{key+1}}. Grade : {{g}}</li>
        </ul>
        <div>
          <label>New Grade:</label>
          <input type="text" v-model="newGrade">
          <button @click="addGrade()">Add</button>
        </div>
        <br>
        <div>
          <p>Average: {{ average }}</p>
        </div>
      </div>
    </div>
  `,
  name: 'Calculator',
  data: () => ({
    grades: [],
    newGrade: 0,
    avg: 0
    //TEST
  }),
  computed: {
    average() {
      return this.grades.length ? `${this.calcAvg(this.grades)}` : "n/a";
    }
  },
  methods: {
    calcAvg(grades) {
      return grades.reduce((a, b) => Number(a) + Number(b), 0) / grades.length;
    },
    addGrade() {
      this.grades.push(this.newGrade);
      this.newGrade = 0;
    }
  }
});
new Vue({
  el: '#app'
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <Calculator />
</div>

For usage with Single File Components (SFC): https://codesandbox.io/s/zealous-ellis-0m0p2


There exist various methods for creating components in Vue:

  • new Vue({ el: '#elId' }) - Replaces the specified element using its contents as a template
  • Vue.extend({}) - Commonly employed in TypeScript applications for inheritance purposes
  • Defining components as classes with @Component decorator when utilizing the vue-class-component plugin (essentially a wrapper around Vue.extend(), at its core)

While there may be alternative approaches, the ones highlighted above are the most prevalent.

Answer №2

Just a few minor tweaks can make all the difference.

data: {
  grades: [],
  newGrade: 0,
  average: 0, // Update this
  total: 0,
},

Replace this:

return total / this.grades.length;

with this:

this.total = total / this.grades.length;

Answer №3

To easily include the data and methods sections in the export default part, simply follow these steps.

export default {
  name:"Mexico",
  props:[], // add properties here
  data:()=>{
      return {
         // define your data variables here
      }
  },
  methods:{
     // define your methods here
  }
}

When structuring a Vue.js component, the html template is directly connected to the export default section. If you utilize a method within the template, ensure it is located within the methods section of the export default.

Answer №4

When working with vueCLI, there's no need to redeclare your app element, as it's already been declared for you in the "App.vue" component within the "src" directory. Make a slight adjustment to your script like this:

<script>
    export default {
        name: "Spain",
        props: {},

        data() {
           return {
              grades: [],
              newGrade: 0,
              avg: 0,
              sum: 0,
              //TEST
           }
        },
        methods: {
          addGrade() {
            this.grades.push(this.newGrade)
            this.newGrade = 0
          },
          calcAvg() {
            let sum = 0;
            for (let i = 0; i < this.grades.length; i++) {
              let num = parseInt(this.grades[i]);
              sum = sum + num;
            }
            //calculate average and display it
            console.log(sum)
            console.log(this.grades.length)
            this.sum = sum / this.grades.length;
          }
        }
    };
</script>

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

Send information to a different module

I've created a straightforward form component: <template> <div> <form @submit.prevent="addItem"> <input type="text" v-model="text"> <input type="hidden" v-model="id"> <i ...

Utilizing Node.js modules in a frontend HTML file with the help of browserify

I am encountering difficulty using a node.js module on my website with browserify. The example provided only demonstrates how to run a separate JavaScript file, not how to incorporate the node.js module within the .html file itself. This seemingly simple i ...

What is the best way to extract the value associated with the "first_name" key in the given object?

What is the best way to extract the value associated with the first_name key from the object below? { "first_name": "D", "last_name": "N", "phone_number": 1233414234 } ...

What is the best way to modify the URL path to eliminate a specific parameter?

Recently, I integrated authentication into my Vue.js application utilizing Amazon AWS Cognito. Although the authentication is functioning properly, I am looking to tidy up the URL and so far have not been successful in doing so. Following authentication w ...

Enhance Your Browsing Experience with this Chrome Extension for Page Interactions

Recently, I came across Chrome extensions and have been intrigued by their functionality. One question that has been on my mind is: how can I programmatically trigger a button click when the extension runs? For instance, there is a button with the id &apos ...

What is the most effective method for implementing a fallback image in NextJS?

Lately, I've been immersed in a NextJS project that involves utilizing the YoutubeAPI to retrieve video details, such as thumbnail URLs. When it comes to fetching a full resolution image, the thumbnail URL typically follows this format: https://i.yti ...

The div background image in Vue.js is displaying a 404 not found error

I've encountered an issue while trying to set a background for a div. Strangely, when using the same relative path with an img tag everything works fine, but as soon as I try to achieve the same result with a div, I receive a 404 error. This img tag ...

Using Ajax, the script triggers calls upon detecting keyup events on various input fields, each

I'm encountering issues while attempting to solve this logic puzzle. The page contains multiple fields and the goal is to store the input values in the database when the user finishes typing. Here's the code snippet: var debounce = null; ...

Using Typescript to replicate Object.defineProperties

Is there a way to emulate Object.defineProperties from JavaScript in Typescript? I am interested in achieving something similar using the syntax of Typescript: Object.defineProperties(someObject.prototype, { property: {get: function() { return v ...

Retrieve the elements by their IDs in an svg where the ID equals '@data[]'

As I load data from SQL in a while loop to create my SVG, each record has its own ID. However, when attempting to retrieve the ID using getelementbyId, it consistently returns null values. Below is the code snippet: #!/usr/bin/perl use DBI; use CGI::Carp ...

Specialized directive for preventing component creation

I developed a custom directive that checks user roles to determine whether or not a component should be shown. Vue.directive("permission", { bind(el, binding) { Vue.nextTick(() => { el.vFillMarkerNode = document.createComment(''); ...

What is the process for converting this code to HTML format?

I am new to programming and I am using an API with node.js to display the result in a browser. The API is working fine with console.log, but I want to render it on the browser instead. I am using Jade template for this purpose. How can I write the code t ...

The directive in Angular compels the webpage to carry out the added HTML attribute

There is a custom directive in my code that applies the spellcheck attribute to two div elements as shown below: (function(){ 'use strict'; app.directive('spellchecker', spellchecker); spellchecker.$inject = ['$timeout&a ...

What are the steps to utilizing an npm package that simply encapsulates my JavaScript code?

Our current npm package is designed for clients working on ES6-based projects, such as React. The main index file of the package looks like this: export function ourFunction() { } Clients import this function using the following syntax: import { ourFunc ...

Nuxt router directing to incorrect URL upon refreshing the page

Let me show you exactly what I mean by setting up a demo Nuxt blog at https://example.com/nuxtblog/. This demonstration includes articles populated by the @nuxt/content package. The website has been generated statically using the nuxt generate command. Fol ...

Linking Java objects with Node.js variables

In this snippet of code, I am utilizing the 'java' module in node.js to create Java objects. Specifically, I am creating four Java objects and aiming to consolidate them as a single object by using the variable 'args' to store these Jav ...

Challenges of Vue 3 Typescript ComputedRef

I've run into some challenges with Typescript and Vue3. It seems like I might be using Typescript incorrectly in this case. I set up a store using Vue's Composition API. import {computed, reactive} from "vue"; const state = reactive({ ...

`How can I implement text alignment in the tiptap editor?`

Using the tiptap vuetify editor within nuxt js has been smooth sailing so far. However, one drawback is that it lacks any text-align properties! Here's a glimpse of my component editor: <template> <tiptap-vuetify :value="valu ...

Using the `map()` method in React's array

I stumbled upon an interesting example at http://codepen.io/lacker/pen/vXpAgj that closely resembles my current issue. Let's consider the following array: [ {category: 'Sporting Goods', price: '$49.99', stocked: true, name: &apo ...

JavaScript function unable to execute form action properly

I have a link RESET YEAR which triggers a servlet to check if the current year is equal to the present year. If they are not equal, then the function resetyear() is supposed to be called. The issue I am facing is that the function is not working as expecte ...