Vue.js is unable to reach a component's method

I have two Vue.js components Lobby and Game. My goal is to utilize Game as a model that holds all the necessary logic for creating a game, which can then be triggered through interactions in the Lobby component.

Whenever I try to run the application and click on the button, it results in the following error:

Uncaught TypeError: game.createGame is not a function
    at click (eval at createFunction (vue.js:9923), <anonymous>:2:76)
    at HTMLButtonElement.invoker (vue.js:1827)

I'm seeking guidance on how to properly access the game method from within the Lobby component. Any help would be greatly appreciated! Thanks!

    let Game = {        
        methods: {
            createGame: function () {
                console.log('createGame clicked')
            }
        }
    }



    let Lobby = {
        template: `
            <div>
                    <button v-on:click="game.createGame()">Create</button>
            </div>
        `,
        data()  {
            return {
                'game': Game
            }
        },

    }

Answer №1

To easily call a method in another component, consider using the Event bus feature provided by Vue.js. The concept is simple: emit a global call from Component A and listen for it in Component B using bus.$on.

var bus = new Vue();

Vue.component('Increment', {
  template: "#inc",
  data: function() {
    return ({count: 0})
  },
  methods: {
    increment: function(){
      var increment = ++this.count
      bus.$emit('inc', increment)
    }
  }
})

Vue.component('Display', {
  template: "#display",
  data: function(){
    return {count: 0}
  },
  created: function(){
    bus.$on('inc', function(num){
       this.count = num    
  }.bind(this));
  }
})


vm = new Vue({
  el: "#example",
})

Check out the implementation on jsFiddle.

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

Combining several reactive arrays into one using Array.flat() may result in a loss of reactivity

I've been developing a component that takes a reactive Map<string, string[]> as input and consolidates all the values in this Map into a single array. The resulting flattened array is then placed into a reactive object that is linked to the temp ...

The functionality of TypeScript's instanceof operator may fail when the method argument is not a simple object

There seems to be an issue with a method that is being called from two different places but returns false for both argument types. Despite checking for the correct types, the problem persists and I am unsure why. Although I have read a similar question on ...

Is there a way to modify the value of a constructor key once it has already been defined?

I am currently working on a simple constructor exercise where I need to update a value after the constructor has been created. Even after changing the value to true, the cat is still not making its noise. Challenge parameters The constructor function wi ...

Deciphering JSON data within AngularJS

When I retrieve JSON data in my controller using $http.get, it looks like this: $http.get('http://webapp-app4car.rhcloud.com/product/feed.json').success(function(data) The retrieved data is in JSON format and I need to access the value correspo ...

Concealing and revealing information with jQuery and AJAX

Need help hiding a Message and displaying an alert message after 5 seconds, but it's not working. What I want is for the Message to be hidden and show an alert message 5 seconds after clicking submit. <script> $(document).ready(function () { ...

Having difficulty sending emails with Nodemailer

This is a simple example showcasing the usage of Nodemailer library. var http = require('http'); var port = process.env.PORT || 8080; var async = require('async'); var nodemailer = require('nodemailer'); // Creating a transp ...

"Enhance your Vue components with a directive to customize or adjust element attributes

I have a variety of elements structured like this: <some-custom-component :errors="formErrors.has(getErrorKey('town'))" :error-messages="formErrors.getAll(getErrorKey('town'))" ></some-custom-component> The formErrors ...

Animate the expansion and shrinkage of a div instantly using jQuery

I am trying to create an animation effect using jQuery animate on a div element where it starts large and then becomes smaller. Here is the code I have written: $(this).animate({ opacity: 0, top: "-=100", width: "38px", height: "32px" }, 1 ...

Problem with a dropdown menu within a dynamically generated table in an HTML/PHP file

I've been experimenting with creating a drop-down table row below another one within a semi auto-generated table. After some research, I discovered that directly animating table elements is not possible. However, when I wrapped my table in a div, the ...

Are you able to locate <td>s with identical classes using just a portion of the string?

There are multiple classes in the <td>s of my table. I am looking to identify each <td> that contains a specific string. For instance: <table> <tr> <td class="hello there">foo</td> <td class=" ...

When users visit my contact HTML page, they are redirected to the contact PHP page, but unfortunately, the email is

I am currently facing an issue with my contact form. After filling out the form and hitting the "send" button, it redirects to the contact.php page but fails to send an email or work as intended. Can someone please assist me and identify what's causin ...

Using Ajax to poll a Celery task

I am working on a Celery task that updates a PostgreSQL database gradually. In my Django application, I want to fetch the latest data from the database and display it in a template in real-time as the task progresses. I am looking to implement this real-ti ...

What is the best way to neatly import multiple images in Next.js?

I have a dilemma involving 10 images located in my public directory that I need to use in a component. Instead of individually importing each image like this: import imgurl1 from "../../public/celsius.gif"; import imgurl2 from "../../public/ ...

I have a website hosted on Heroku and I am looking to add a blog feature to it. I initially experimented with Butter CMS, but I found it to be too pricey for my budget. Any suggestions on

I currently have a website running on Heroku with React on the front end and Node.Js on the back end. I want to incorporate a blog into the site, but after exploring ButterCMS, I found the pricing starting at $49 to be too steep for my budget. My goal is ...

What is the best way to ensure that a server response is received before initiating an Apollo Graph QL Query

Is there a way to call a Graph QL Query after data is received from the useEffect hook? The challenge I am facing is that hooks cannot be called conditionally. If I remove the condition, loadedAnime will become undefined. How can I overcome this limitati ...

Performing AJAX requests within AJAX requests without specifying a callback function for success

Upon reviewing this discussion jQuery Ajax Request inside Ajax Request Hello everyone, I'm in need of some clarification on a particular scenario. I recently took over the code from a former member of my development team and noticed that they have ma ...

What is the origin of TrackballControls?

Seeking to enhance camera control within a threejs environment. After examining this specific demo, it appears that the functionality is largely achieved through the following lines of code: controls = new THREE.TrackballControls( camera ); controls.rota ...

Implementing jquery document.ready() with <img onload> event

My current need is to trigger a JavaScript function each time an image loads on the page, but I also require that the DOM of the page is fully loaded before the script executes. I have provided a sample example below and would appreciate feedback on wheth ...

Should Vue components be incorporated into blade templates as a best practice?

I have incorporated multiple Vue components into a Laravel blade template as shown below: <div id="app"> <user-list></user-list> <first-component></first-component> <seconde-component> ...

Nightmare JS randomly selecting and clicking on a link from a defined set

When coding with Nightmare JS, I am faced with a challenge. I want to click on a link using the method nightmare.click("#video-title"). However, this clicks the first element with that id. Upon running document.querySelectorAll('[id=video-title]' ...