我的模板:
<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> </a>
<a href="#" class="btn btn-primary btn-info" data-toggle="tooltip" data-placement="bottom" title="Pokaż profil"><span class="glyphicon glyphicon-user"></span> </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> </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
。我不知道如何在组件模板中使用方法。如果有人可以帮助我,我会很感激。
答案 0 :(得分:10)
如果您需要将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);
}
}
});
答案 1 :(得分:2)
您的方法应该在组件中,而不是在全局Vue实例中。所有函数在幕后都被称为this.createConversation
,因此它需要位于作为模板的组件内。