2016-01-15 46 views
8

我的模板:调用函数

<template id="players-template" inline-template> 
     <div v-for="player in players"> 
      <div v-bind:class="{ 'row': ($index + 1) % 3 == 0 }"> 
       <div class="player col-md-4"> 
        <div class="panel panel-default"> 
         <div class="panel-heading"> 
          <h3 class="panel-title"> 
           <a href="#">{{ player.username }}</a> 
           <span class="small pull-right">{{ player.createdAt }}</span> 
          </h3> 
         </div> 

         <div class="panel-body"> 
          <img v-bind:src="player.avatar" alt="{{ player.username }}" class="img-circle center-block"> 
         </div> 
         <div class="panel-footer"> 
          <div class="btn-group btn-group-justified" role="group" aria-label="..."> 
           <a href="#" class="btn btn-primary btn-success send-message" data-toggle="tooltip" data-placement="bottom" title="Wyślij wiadomość" v-bind:id="player.id" @click="createConversation(player.id)"><span class="glyphicon glyphicon-envelope"></span>&nbsp;</a> 
           <a href="#" class="btn btn-primary btn-info" data-toggle="tooltip" data-placement="bottom" title="Pokaż profil"><span class="glyphicon glyphicon-user"></span>&nbsp;</a> 
           <a href="#" class="btn btn-primary btn-primary" data-toggle="tooltip" data-placement="bottom" title="Zobacz szczegółowe informacje o poście"><span class="glyphicon glyphicon-option-horizontal"></span>&nbsp;</a> 
          </div> 
         </div> 
        </div> 
       </div> 
      </div> 
     </div> 
    </template> 

我的脚本:

new Vue({ 
    el: 'body', 
    methods: { 
     createConversation: function(id) { 
      console.log("createConversation()"); 
      console.log(id); 
     } 
    } 
}); 

当模板被渲染我得到一个错误[Vue warn]: v-on:click="createConversation" expects a function value, got undefined。我不知道如何在组件模板中使用方法。如果有人能帮助我,我将不胜感激。

回答

2

你的方法应该在组件中,而不是在你的全局Vue实例中。所有功能在幕后都被称为this.createConversation,所以它需要位于作为模板的组件之内。

+0

我不希望在该组件这一功能,因为它会产生完全不同。模板从数据库获取用户并显示它们。然后,当我点击按钮时,我想创建新的对话。 – nix9

+0

您可以使用其他答案中的事件,也可以使用'this。$ root'访问根Vue实例。所以在你的点击事件中,你可以使用'$ root.createConversation(player.id)'。我鼓励你尝试构建你的组件,以便每个组件管理它自己的功能,这是最好的可重用性和Vue的核心概念。 – Jeff

+0

我想构建我的应用程序。这就是为什么我不想混合不同的功能。 – nix9

8

如果您需要将createConversation方法放在全局Vue实例上,则应查看dispatching events。你的组件应该是这样的:

Vue.component('playersTemplate', { 
    template: '#players-template', 
    methods: { 
    createConversation: function (id) { 
     this.$dispatch('createConversation', id) 
     } 
    } 
    } 
}); 

全球Vue的实例应该实现createConversation事件,而不是一个方法:

new Vue({ 
    el: 'body', 
    events: { 
     createConversation: function(id) { 
      console.log("createConversation()"); 
      console.log(id); 
     } 
    } 
}); 
+0

这就是我所需要的。 – nix9

+0

然后请将此标记为正确的答案,谢谢。 – Gus

+0

我该怎么做? – nix9