KinectUser
KinectUser

Reputation: 31

How to call method from template in Vue.js?

I have my vue instance:

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:

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

Upvotes: 1

Views: 15354

Answers (1)

Dawid Zbiński
Dawid Zbiński

Reputation: 5826

Yes, it is possible. Instead of calling the function inside each share, just pass the reference to it. You need to use 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.

Fiddle: http://jsfiddle.net/vnef5d4c/11/

Upvotes: 3

Related Questions