【问题标题】:Vue.js – Passing functions in array as a propVue.js – 将数组中的函数作为道具传递
【发布时间】:2021-02-17 12:07:25
【问题描述】:

导航栏.vue

组件NavigationBar.vue 在我的Vue.js 应用程序中使用,接受以下道具:

props: {
    title: String,
    actions: Array
}

这是NavigationBar 组件:

该组件接受数组以使用v-for 生成右侧的操作按钮。它们在父文件中定义,并且根据我的应用程序中的位置而有所不同。如果点击按钮,则需要调用指定的函数。

成员.vue

Members.vue 是父级。请注意其中的组件、操作和功能:

<template>
    <div>   
        <NavigationBar title='Members' actions="actionsArray" ></NavigationBar
    </div>  
</template>

<script>
import ...

export default {
  name: 'members',
  components: {
    NavigationBar
  },
  data () {
    return {
        actionsArray: [
            { btnText: 'Create', icon: 'mdi-plus-circle', function: 'createBtnClicked()' },
            { btnText: 'Edit', icon: 'mdi-pencil', function: 'editBtnClicked()' },
        ],
  }
  methods: {
    createBtnClicked() {
        // amazing things will happen here
    },
    editBtnClicked() {
        // it will be even greater when this button is clicked
    },
}

</script>

问题:

我无法让按钮的功能正常工作。将函数作为道具传递是否是正确的方法?

非常感谢您的帮助!谢谢:)

【问题讨论】:

  • 为按钮使用插槽,这也将使您在按钮布局方面更加灵活
  • @minychillo 谢谢。我决定使用插槽,因为我已经到了需要这种灵活性和自定义选项的地步。

标签: vue.js vue-component


【解决方案1】:

您似乎在传递字符串而不是实际函数。

尝试以下方法:

data () {
    return {
      actionsArray: [
        { btnText: 'Create', icon: 'mdi-plus-circle', function: this.createBtnClicked },
        { btnText: 'Edit', icon: 'mdi-pencil', function: this.editBtnClicked },
      ],
}

也许考虑明确声明 prop types 以使分配给 props 的 Vue 检查值具有正确的类型。

【讨论】:

  • 在这种情况下不会使用 function(){} 比箭头函数更好,因为 this 绑定到父级,并且限制之一是箭头函数没有自己的绑定到thissuper ??
  • 根本不需要包装函数。只需执行function: this.createBtnClicked。请注意末尾缺少括号。
  • @gogo 感谢您的回答。但是我现在决定改用插槽。它们在我的应用中为我提供了更多的灵活性和选择。
猜你喜欢
  • 2015-09-16
  • 2020-07-12
  • 2019-11-05
  • 2022-08-12
  • 2019-07-03
  • 2020-08-28
  • 1970-01-01
  • 1970-01-01
  • 2017-01-21
相关资源
最近更新 更多