VueJS - 方法中的动态函数名称

VueJS - dynamic function name inside methods

我有一个列表和导航,它是根据数据行数用 12 items/page 生成的。

我的导航按钮触发 vue-js v-on:click 事件

我也在尝试在 JS 文件中动态生成函数方法,但似乎无法在方法部分放入循环语句。不断收到语法错误。

vueJS 方法部分是否有特定的 JS 语法?

        methods: {

        for (x = 0; x < 2; x++){
            featuredStores.'x' = function(){
                 for (y = 0; y < 2; y++)
                this.storeFeatNav.'y' = !this.storeFeatNav.'y'
        }}

如果有帮助,我也在使用 Laravel 框架。

谢谢

显然您想动态添加方法,但不清楚您在动态方法附件代码中做了什么。因此,我将向您展示一种动态添加方法的方法,例如:

var methods = {
    greet() {
        console.log(this.message + ' from greet method.');
    }
};

for (let x = 0; x < 2; x++)  {
    methods['featuredStores'+x] = function() {
        console.log(this.message + ' from featuredStores'+x+' method.');
    }
}

请注意,methods['featuredStores'+x] 实际上是通过在循环内将 x 的值与字符串 featuredStores 连接起来来创建方法名称,因此第一次 [=16] 的值=] 是 0 产生 featuredStores0 第二次 x 的值是 1 所以它产生 featuredStores0 最后你有三种方法是:

greet // hard coded
featuredStores0 // added dynamically within the loop
featuredStores1 // added dynamically within the loop

现在,您只需在创建Vue实例时将methods对象添加为新实例的属性即可,例如:

var demo = new Vue({
    el: '#demo',
    methods: methods, // or just methods
    data:{
        message: "Hello World"
    }
});

要查看实际效果,请运行以下代码片段(希望这会给您一些想法):

var methods = {
    greet() {
        console.log(this.message + ' from greet method.');
    }
};

for (let x = 0; x < 2; x++)  {
    methods['featuredStores'+x] = function() {
        console.log(this.message + ' from featuredStores'+x+' method.');
    }
}

var demo = new Vue({
    el: '#demo',
    methods,
    data:{
        message: "Hello World"
    },
    created() {
     this.greet();
        this.featuredStores0();
 this.featuredStores1();
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/0.8.6/vue.min.js"></script>
<div id="demo">
    {{message}}
</div>