繁体   English   中英

在Vue.js模板中调用函数

[英]Calling functions inside Vue.js template

我的模板:

<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 我不知道如何在组件模板中使用方法。 如果有人可以帮助我,我会很感激。

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

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);
        }
    }
});

您的方法应该在组件中,而不是在全局Vue实例中。 所有函数都在幕后调用this.createConversation ,因此它需要位于作为模板的组件内。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM