javascript - How to call method from template in Vue.js? - Stack Overflow

I have my vue instance:var testOptions = new Vue({el: '#testOptions',methods: {getURL: functi

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>

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>
Share Improve this question edited Nov 28, 2018 at 8:41 tony19 139k23 gold badges277 silver badges347 bronze badges asked Nov 28, 2018 at 8:35 KinectUserKinectUser 312 gold badges2 silver badges11 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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 ponent.

Fiddle: http://jsfiddle/vnef5d4c/11/

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744303196a4567601.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信