【问题标题】:VueJS - dynamic function name inside methodsVueJS - 方法内的动态函数名称
【发布时间】:2018-12-15 07:17:41
【问题描述】:

我有一个列表和导航,它根据数据行数生成 12 个项目/页。

我的导航按钮触发 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 框架。

谢谢

【问题讨论】:

  • 好像this.storeFeatNav[x]
  • @Sphinx - 似乎没有用。即使在 for 语句中,我也会陷入困境

标签: laravel vue.js


【解决方案1】:

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

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 连接来创建方法名称,因此x 的值第一次是0,从而产生@987654327 @ 和第二次 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"
    }
});

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

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>

【讨论】:

  • 您好@The Alpha,感谢您抽出宝贵时间了解我的问题。这个解决方案正是我正在寻找的。最重要的是,我学会了如何在这个论坛中更好地提出问题
  • 欢迎您!很高兴知道:-)
猜你喜欢
  • 2019-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-13
  • 1970-01-01
  • 2013-09-27
  • 2018-03-21
  • 2016-11-12
相关资源
最近更新 更多