简体   繁体   English

如何从Vue.js中的模板调用方法?

[英]How to call method from template in Vue.js?

I have my vue instance: 我有我的Vue实例:

var testOptions = new Vue({
    el: '#testOptions',
    methods: {
        getURL: function () {
            return (window.location.href);
        },
        testOne: function () {
            console.log('!!');
        },
        testTwo: function () {
            console.log('!!!!');
        }
    },
    data: {
        shares: [
            { text: 'testOne', icon: 'ico_test1.svg',func: testOne() },
            { text: 'testTwo', icon: 'ico_test2.svg', func: testTwo() },
        ]
    }
});

Is it possible to call my method testOne / testTwo which I pass to shares array like this: 是否可以叫我的方法testOne / testTwo我传给shares数组是这样的:

<li v-on:click="share.func" class="test-options__option">
    {{share.text}}
</li>

Yes, it is possible. 对的,这是可能的。 Instead of calling the function inside each share, just pass the reference to it. 无需在每个共享内部调用函数,只需将引用传递给它。 You need to use this. 您需要使用this. as those are instance functions. 因为这些是实例函数。

shares: [
    { text: 'testOne' icon: 'ico_test1.svg', func: this.testOne },
    { text: 'testTwo' icon: 'ico_test2.svg', func: this.testTwo },
]

Also, data property should be a Function that returns object (the actual data) and it's a good practice to add that property onto the top of your Vue component. 另外, data属性应该是一个返回对象(实际数据)的Function ,这是将该属性添加到Vue组件顶部的一种好习惯。

Fiddle: http://jsfiddle.net/vnef5d4c/11/ 小提琴: http : //jsfiddle.net/vnef5d4c/11/

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

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