1

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>

1 Answer 1

3

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/

Sign up to request clarification or add additional context in comments.

4 Comments

didn't you update your code in some way? any errors it's throwing? Also, the data property should be a function if it's not the main component, but in your case that's not a problem, if the code is the same as you shared.
when I click on li I am not getting any errors but on page load I got error : Invalid handler for event "click": got undefined. In Vue Devtools I see that reference to my methods are equal to undefined for each li
That's probably because data is not a function. Try changing those data property to function that returns data object. data: function () { return { /* data */ } }
When data property is not a function this is not pointing on the Vue instance but the different scope instead. You should write data as a function most of the times.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.