I am attempting to rebuild Vuex's Getting Started example by utilizing multiple components, yet I am struggling to understand how to call root methods from within these components

The project I'm working on can be found here. It is a simple one, but for the purpose of learning, I divided it into index and four js files (parent, child, root, and store). My challenge lies in figuring out how to call the increment and decrement root methods in the child component without resorting to commits within the elements or engaging in poor practices like using props or this.$root inside the components.

Here is the code breakdown:

index.html:

<div id="app">
        <parent></parent>
</div>

root.js:

let vm = new Vue({
    el: '#app',
    store,
    methods:{
        increment(){
            store.commit('incrementar')
        },
        decrement(){
            store.commit('decrementar')
        } 
    }
})

store.js:

const store = new Vuex.Store({
    state:{
        numero: 11
    },
    mutations:{
        incrementar(state){
            state.numero++
        },
        decrementar(state){
            state.numero--
        }
    }
})

parent.js:

Vue.component('parent',{
    template:
    `
    <div>
        <h1>Number: {{$store.state.number}}</h1>
        <child></child>
    </div>
    `
})

child.js:

Vue.component('child',{
    template:
    `
    <div>
        <button @click="increment">+</button>
        <button @click="decrement">-</button>
        <h1>Number: {{number}}</h1>
    </div>
    `,
    computed: {
        number() {
            return store.state.number
        }
      }

I have read that events should be used, but I am unsure about implementing them with the buttons. Keep in mind that I am relatively new to JavaScript, Vue, and Vuex.

Answer №1

If you want to utilize instance methods events, refer to the documentation here. An example code snippet is provided below:

root.js:

let vm = new Vue({
    el: '#app',
    store,
  mounted () {
    let self = this
    self.$root.$on('FancyEventName', self.HandleFancyEvent)
  },
  beforeDestroy () {
    let self = this
    self.$root.$off('FancyEventName', self.HandleFancyEvent)
  },
  methods: {
    HandleFancyEvent (arg) {
      let self = this
      if(arg === true){
       self.increment()
     } else{
       self.decrement()
     }
    },
    methods:{
        increment(){
            store.commit('incrementar')
        },
        decrement(){
            store.commit('decrementar')
        } 
    }
})

child.js:

Vue.component('child',{
    template:
    `
    <div>
        <button @click="increment">+</button>
        <button @click="decrement">-</button>
        <h1>Numero: {{numero}}</h1>
    </div>
    `,
    methods:{
        increment(){
            let self = this
            self.$root.$emit('FancyEventName', true)
        },
        decrement(){
            let self = this
            self.$root.$emit('FancyEventName', false)
        } 
    }
    computed: {
        numero() {
            return store.state.numero
        }
      }

This setup will function effectively. Additionally, an alternate approach involves creating a separate event bus for communication:

// event-bus.js
import Vue from 'vue';
const EventBus = new Vue();
export default EventBus;

Here is how you can use the Event Bus in components:

// component-a.js
import Vue from 'vue';
import EventBus from './event-bus';
Vue.component('component-a', {
  ...
  methods: {
    emitMethod () {
       EventBus.$emit('EVENT_NAME', payLoad);
    }
  }
});

And a second component which reacts to this event:

// component-b.js
import Vue from 'vue';
import EventBus from './event-bus';
Vue.component(‘component-b’, {
  ...
  mounted () {
    EventBus.$on(‘EVENT_NAME’, function (payLoad) {
      ...
    });
  }
});

Both methods achieve the same result, with the only distinction being the utilization of a separate instance for communication purposes.

I hope this explanation proves helpful! 🙂

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

Getting the value of a variable within the scope of AngularJS can be achieved by utilizing

I have an ng-repeat directive in my code that displays slides. Here is a snippet of the data: slides = [{ src: "/sikiosk/slidedata/Global/NA/USNS/Cafeteria/5000_24.jpg", interval: 5000 }, { src: "/sikiosk/slidedata/Global/NA/USNS/Cafeteria/5000_login-regi ...

"Exciting Changes in Color According to the Active State of vue-route-link

I am trying to find a way to customize the CSS based on whether a link is exact or active. Essentially, when a user clicks on a menu item, I want the underline to change depending on whether the link is an active router-link. Although I was able to accompl ...

Tips for loading a webpage directly to the center instead of the top position

Is there a way to make the page open at a specific div halfway down the page instead of starting from the top? Here is an example: <div id="d1"> <div id="d2"> <div id="d3"> <div id="d4"> <div id="d5"> <div id="d6"> Do ...

Obtain the node identifier within the Angular UI Tree component [angular-ui-tree]

Utilizing Angular UI tree to create a relationship between items and categories has been successful in the default setup. However, a new requirement has emerged to incorporate node/section numbering within the tree for managing hierarchy. I attempted to i ...

Playing with Data in AG-Grid using Javascript

I am working on implementing data display using AG Grid with an AJAX call, but I am facing an issue where no data is being shown in the grid. Even though my AJAX call seems to be functioning correctly and returning the desired object List, the grid itsel ...

Adjusting Headers Using Buttons

Having some issues with my JavaScript code. I'm trying to achieve a specific functionality where clicking the "Modify HTML content" button changes the h1 heading from "The Original Content" to "The New Content", and vice versa on subsequent clicks. Si ...

Exploring the impact of JavaScript tags on website performance in accordance with W3

While researching website optimization strategies today, I came across an article discussing the benefits of moving JavaScript scripts to the bottom of the HTML page. I am curious if this approach aligns with W3C's recommendations since traditionally ...

Optimizing HTML and Script loading sequences for efficient execution

I have a query regarding the loading order of scripts in web browsers. I am interested in knowing the most efficient way to redirect users to a mobile website on the client side. For example, if I place a mobile detection script within the <head> se ...

Tips for differentiating between elements with identical values in an HTML datalist using Angular

My boss is insisting that I use a datalist in our website interface to select an employee, even though there's no way to determine if the user typed in the name or picked from the list. The challenge is that the list must only display full names, but ...

Is there a way to invoke a component with a unique data property in vue.js 2?

This is how I see it: <!-- From Players --> <div class="row no-gutter"> <div class="col-md-3"> <h2 class="nav-cat-text">From Players</h2> </div> <div class="col-md-9 col-xs-12"> <div ...

What is the method employed by the script to ascertain the value of n within the function(n)?

I've recently started learning about jQuery. I came across a program online that uses a function where the value of n starts from 0 and goes up to the total number of elements. In the example below, there is only one img element and jQuery targets thi ...

Guide on setting up a route in Next.js

Recently, I developed a simple feature that enables users to switch between languages on a webpage by adding the language code directly after the URL - i18n-next. Here's a snippet of how it functions: const [languages, ] = React.useState([{ langua ...

I encountered an issue while starting the VueJS build where an error message appeared stating: "Conflict: Multiple assets emit

After updating VueJS this morning, my app started encountering an issue. When I try to build it, an error message pops up stating: Error: Conflict: Multiple assets emit to the same filename img/default-contractor-logo.0346290f.svg Despite there being onl ...

Error encountered in NextJS: Trying to call res.unstable_revalidate which is not a function

I recently tried out a cutting-edge feature introduced in NextJS v.12.1 . The API itself is functioning correctly and can be accessed. However, I encountered a 500 error with the message res.unstable_revalidate is not a function. This issue persisted wheth ...

Having trouble setting a value in a Vue.js variable

Upon assigning a value retrieved from the firebase collection, I encountered the following error message. Error getting document: TypeError: Cannot set property 'email' of undefined at eval (Profile.vue?5a88:68) Here is the code snippet in que ...

Modifying the Path for Vite Manifest File

I'm encountering an issue where the Vite manifest is not being found at public_html/public/build/manifest.json on my website. I would like it to be available in the public_html/build/ directory instead. How can I modify my configuration to achieve thi ...

Tips for sending a request from a Nuxt.js client through a Nuxt.js server and successfully receiving the response on the client side

I am currently working on a Vue.js application that operates solely on the frontend with no server involved. The app sends multiple requests to various APIs, resulting in its complexity increasing over time. Unfortunately, some of these APIs pose problems ...

Switching images dynamically using Flask and JavaScript

I'm currently working on Flask and encountering a perplexing issue. I'm attempting to update an image using JavaScript, but I am getting these errors from Flask: ... 12:05:34] "GET / HTTP/1.1" 200 - ... 12:05:38] "GET /img/pictur ...

Dynamic links with Node Acl

Utilizing the npm module Acl to establish an ACL system has been my current focus. You can check out the homepage of this module at: https://github.com/OptimalBits/node_acl. While the documentation provides straightforward examples for granting role acces ...

How can I determine when a WebSocket connection is closed after a user exits the browser?

Incorporating HTML5 websocket and nodejs in my project has allowed me to develop a basic chat function. Thus far, everything is functioning as expected. However, I am faced with the challenge of determining how to identify if connected users have lost th ...