2017-09-23 121 views
0

我有两个Vue.js组件大厅游戏。我想用游戏作为一个模型,包含所有创建游戏并通过大厅组件触发它的逻辑。Vue.js无法访问组件的方法

如果我运行应用程序,并单击按钮,我碰到下面的错误

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) 

如何访问从大堂组件游戏的方法?谢谢!

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 
      } 
     }, 

    } 
+0

把它包装的游戏方法,并调用它的方式在大堂的方法。但是,这看起来像你使用该代码一样不好的做法。如果模板位于游戏组件中,并且您使用Lobby上的插槽来嵌套游戏组件,会更有意义。 – Shay

+0

你可以把整个代码得到组件的分层思路吗? – Thusitha

回答

0

如果你想从另一个调用组件的方法,你可以使用Event bus从Vue.js 的主要思想是,你必须在一个组件发出的全球呼吁,并使用bus.$on

接受它在B组分
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", 
}) 

https://jsfiddle.net/emwcoy36/

+0

谢谢。我的头两个小时vue.js ...似乎是我需要更多地了解这些关系。 – user7646471

+0

如果你是初学者,我可以强烈推荐你关于'vue.js'的这个youtube课程:[youtube.com](https://www.youtube.com/watch?v=5LYrN_cAJoA&list=PL4cUxeGkcC9gQcYgjhBoeQH7wiAyZNrYa) – test