【问题标题】:vueJS : call a method in v-for loopvueJS:在 v-for 循环中调用方法
【发布时间】:2021-12-28 06:16:46
【问题描述】:

我设置了一些buttons,我想使用v-for 创建它们

每个button 都有一个event

这是我的template 代码

<button v-for="(btn,i) in btns" :key="i" @click="btn.action">
  {{btn.text}}
</button>

这是我的script 部分

btns= [
  { text:'print', action: 'print()' } ,
  { text:'another action', action: 'anOtherMethod()' },
]

但我有一个错误

那么,我该如何解决呢?

【问题讨论】:

    标签: vue.js nuxt.js


    【解决方案1】:

    尝试创建另一种方法来处理按钮单击事件,例如:

    <button v-for="(btn,i) in btns" :key="i" @click="handleClick(btn.action)">
      {{btn.text}}
    </button>
    

    并从方法定义中删除()

    btns:[
    {text:'print' , action :'print' } ,
    {text:'another action' , action :'anOtherMethod' } ,
    ]
    

    最后添加使用方括号访问器运行动态方法的处理程序方法:

    methods:{
    handleClick(actionName){
       this[actionName]()
    },
    anOtherMethod(){
    ....
    }
    
    }
    

    【讨论】:

    • 你确定这行得通吗?
    • 是的,我相信这行得通
    【解决方案2】:

    试试看。

    <template>
        <button v-for="(btn, i) in btns" :key="i" @click="btn.action">
            {{btn.text}}
        </button>
    </template>
    <script>
      export default {
        data () {
          return {
            btns: [
                {text:'print' , action: this.print() } ,
                {text:'another action' , action: this.anOtherMethod() } ,
            ]
          }
        },
        methods: {
          goInit () {
            // add print statements
          },
          anOtherMethod() {
            // add anOtherMethod statements
          },
        }
      }
    </script>
    

    【讨论】:

    • 这会注意到工作,当组件被加载时,所有的动作都会被调用
    猜你喜欢
    • 1970-01-01
    • 2020-04-01
    • 2020-05-03
    • 2020-04-04
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-31
    相关资源
    最近更新 更多