Attempting to dispatch data from Vue.js event bus

I am attempting to increase the count of quotes by one and also add the text from a textarea to an array. While the text is successfully added to the array, the number of quotes always remains zero. I have tried combining the two actions in one method as well as separating them, but I consistently get the same result.

<template>
    <div>
       <p>Quotes</p>
        <b-form-textarea
      id="textarea-rows"
      v-model="value"
      placeholder="Enter something..."
      rows="5"
    ></b-form-textarea>
    <b-button variant="primary" @click='plusOneQuote(); addQuote();'>Add Quote</b-button>
    </div>
</template>

<script>
import {EventBus} from '../main.js'

export default {
        props: ['numberOfQuotes', 'quotes'],
        data (){
            return {
                value: '',
            }
        },
        methods: {
            plusOneQuote() {
                this.numberOfQuotes++;
                EventBus.$emit('addedQuote', this.numberOfQuotes);

            },
            addQuote() {
                this.quotes.push(this.value);
            }
        }
}
</script>

Strangely, when I remove the 'addQuote' function from the button click event and method, then the numberOfQuotes value increases by one without any issues and is successfully displayed in another component.

Answer №1

It is considered best practice to call a single method within the click directive, as shown in this example:

<b-button variant="primary" @click='updateQuotes'>Add Quote</b-button> here

Instead of calling multiple methods like this:

<b-button variant="primary" @click='plusOneQuote(); addQuote();'>Add Quote</b-button>

In the methods section, you can define the updateQuotes method to handle both functionalities for better code organization:

methods: {
        plusOneQuote() {
            this.numberOfQuotes++;
            EventBus.$emit('addedQuote', this.numberOfQuotes);
        },
        addQuote() {
            this.quotes.push(this.value);
        },
        updateQuotes(){
             this.plusOneQuote();
             this.addQuote();
        }

If you encounter issues with mutation of a prop directly, consider using getters and setters or utilize a v-model according to the documentation:

Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value.

This approach can help with maintaining clean and efficient code. I hope this solution provides assistance.

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

Dissipating visuals / Effortless website navigation

Do you have experience working with HTML or are you looking for specific code examples? I've noticed some websites with sliders that feature clickable images fading in as soon as the page loads. I tried searching for information on how to achieve thi ...

Using AngularJS to handle form data without ng-model

I am facing a unique situation that may seem a bit strange. I have a form that needs to edit/update information from different objects, such as services. My goal is to use ng-model to link input fields to their respective objects, but when the form is sub ...

Retrieve data from backend table only once within the bootstrap modal

How can I retrieve values from a table once a modal is displayed with a form? I am currently unable to access the values from the table behind the modal. Are there any specific rules to follow? What mistake am I making? I would like to extract the values ...

When altering a single scope variable in AngularJS, the effect cascades to impact other scope variables as well

After uploading my code on fiddle, I noticed that changes made to the myAppObjects variable also affect another variable. Here is the link to the code: https://jsfiddle.net/owze1rcj/ Here is the HTML part of the code: <div ng-controller="MyCtrl"&g ...

The JavaScript functions are not loading within the onload event handler

I've got an HTML document that contains some Script sections. I've consolidated all the functions within a single Script Tag. Now, I want to be able to utilize these methods in both the onload and onclick events. Below is the HTML file with all t ...

What is the most efficient way to transform an array of objects into a compact string?

I'm exploring a new project with an import/export feature in mind. Initially, I will have an array containing approximately 45 simple objects structured like this: {"id": "someId", "quantity": 3} To make it exportable, t ...

Display a unique button and apply a strike-through effect specifically for that individual list item

I've encountered an issue with my code that is causing problems specifically with nested LI elements under the targeted li element: $('#comment-section .comment-box a#un-do').hide(); $('#comment-section ul li[data-is-archived="true"]& ...

What is the best way to leverage multiple random YouTube v3 API keys simultaneously?

I have the following code snippet and I am looking to randomly select an API key from a list of keys: function search() { // Clear Results $('#results').html(''); $('#buttons').html(''); // Get Form Input ...

Can someone help me troubleshoot this issue with my code so that my website can open in a blank page using about:blank?

I'm currently facing an issue while trying to make one of the pages on my website open with an about:blank URL upon loading. Despite embedding the code in my index.html file, it doesn't seem to be functioning properly. Here's the code I&apos ...

Incorporating VueJS with a Dynamic PHP Variable

I am working on binding an HTML element that contains a PHP echoed string so I can leverage it with VueJS. The goal is to switch between GBP and USD based on certain php/mysql database queries (USD being the default value). Let's take a look at what I ...

The Axios plugin in VueJS seems to be getting confused with the URLs, as it is combining 'localhost' with the actual URL causing errors

Recently, I started a project using Vue-cli and encountered an issue with the axios get request not functioning as expected. axios.get("​https://pokeapi.co/api/v2/​pokemon") .then(response => { this.pokemons = response.da ...

Adding flair to a fresh element and then removing it upon its inception

I'm working with a JavaScript code that creates a new element when a button is clicked. I have a question about it. Here's the JavaScript code snippet: var comment = document.querySelector("#AddComment"); var req = new XMLHttpRequest(); if(comm ...

Showcasing events in a horizontal line using Vue-echarts

Seeking guidance on creating a chart using vue-echarts. How can I display events over 24 hours? The data, fetched from an API, consists of objects like: [ { start: "2023-11-01T01:47:09.930Z" end: "2023-11-01T02:47:09.930Z" ...

What are the steps to integrating JavaScript autocomplete into a website?

I am relatively new to the world of programming, particularly when it comes to JavaScript/jQuery. I have been searching online for a solution to enable autocomplete in my search feature, but despite trying various approaches found on the internet, I have y ...

Incorporating the chosen value from a dropdown box as a variable in PHP

Seeking assistance with using the value selected in a drop-down box as a PHP variable in my functions.php file. I attempted to utilize jquery-ajax for this purpose. $(document).ready(function(){ $("#pa_color").change(function(){ var result= $(this).val( ...

The system is unable to locate a compatible object with the identifier '[object Object]' of type 'object'. NgFor is limited to binding with iterables like Arrays, not JSON data

Working with JSON data data:[ { assets:[[tool_order_id: "38",order_status_id: "10"]], order_info:[id: "1", order_type: "6",check: "1", current_Stage_id: "29"] }, { assets:[tool_order_ ...

"ng2-file-uploader necessitates a browser refresh in order to function

I am currently utilizing ng2-file-upload within my Angular 10 project to allow users to upload their photos. The upload process is functioning correctly, but the issue arises when the newly uploaded photo does not automatically appear in the photo list wit ...

How can I efficiently retrieve the name variable of a Quasar (or Vue 3) application?

Is there a way to incorporate something similar in Quasar without having to redefine the variable in every component? <template> <div>Enjoy your time at {{ APP_NAME }}.</div> </template> During the setup of my app with Quasar C ...

Interactive JQuery plugin for scrolling through thumbnails with customizable buttons

I am attempting to create a jQuery thumbnail scroller with buttons that respond to mousedown and mouseup events. I have successfully implemented the scrolling functionality, but I am facing issues when trying to refactor it into a reusable function. Below ...

The issue with Vue email validation not functioning correctly when the div ID is removed

I'm completely new to Vue.js and I'm keen on understanding why removing the div with id "app" in this codepen example (not mine) leads to the failure of rendering the email validator input field. <div class="container" id="app&q ...