0

我目前正在使用 Vue-datatable,我有一个通用的 vue 组件作为 . 我正在使用这个基本组件来呈现数据表,并且我在元素中有一个 @click 事件。但是当我在不同的地方使用这个组件时,我希望 @click 事件被覆盖,这样我就可以根据我的需要调用不同的方法。

下面的文件是 BaseTable.vue

<v-app id="inspire">
  <v-data-table
    v-model="selected"
    :headers="headers"
    :items="desserts"
    :pagination.sync="pagination"
    select-all
    item-key="name"
    class="elevation-1"
  >
    <template v-slot:headers="props">
      <tr>
        <th>
          <v-checkbox
            :input-value="props.all"
            :indeterminate="props.indeterminate"
            primary
            hide-details
            @click.stop="toggleAll"
          ></v-checkbox>
        </th>
        <th
          v-for="header in props.headers"
          :key="header.text"
          :class="['column sortable', pagination.descending ? 'desc' : 'asc', header.value === pagination.sortBy ? 'active' : '']"
          @click="changeSort(header.value)"
        >
          <v-icon small>arrow_upward</v-icon>
          {{ header.text }}
        </th>
      </tr>
    </template>
    <template v-slot:items="props">
      <tr :active="props.selected" @click="props.selected = !props.selected">
        <td>
          <v-checkbox
            :input-value="props.selected"
            primary
            hide-details
          ></v-checkbox>
        </td>
        <td>{{ props.item.name }}</td>
        <td class="text-xs-right">{{ props.item.calories }}</td>
        <td class="text-xs-right">{{ props.item.fat }}</td>
        <td class="text-xs-right">{{ props.item.carbs }}</td>
        <td class="text-xs-right">{{ props.item.protein }}</td>
        <td class="text-xs-right">{{ props.item.iron }}</td>
      </tr>
    </template>
  </v-data-table>
</v-app>
</template>```

Could I possibly override the triggercall method shown above in the code?
Thanks.
4

1 回答 1

0

从您的组件触发一个event,可以从父组件监听。

假设在您的DataTable组件中有button触发 a click

 <button @click="$emit('triggerClick')">
     Hey trigger when someone clicks me
 </button>`

现在你想在哪里使用DataTable组件并想method在有人点击里面的按钮时执行DataTable

简单地 -

<Your-Component>

  <DataTable @triggerClick="yourMethodFoo"/>

</Your-component>

如果您想method在组件内部并可以从父级覆盖它。然后这是您想要的可选行为 - 就像您想要创建一个全局行为。

您需要额外prop告诉您的全局组件您希望方法被父方法覆盖。

props: {
  parentHandler: {
    type: Boolean,
    default: false
  }
}

methods: {
  triggerClick() {
    if (this.parentHandler) {
      this.$emit(triggerClick)
       return
    }
    // execute anything bydefault

  }
}

<button @click="triggerClick">
   Hey trigger when someone clicks me
</button>`

因此,默认情况下,您将执行默认值method,但如果您传递parentHandler= true给组件,它将执行父方法

<Your-Component>
  <DataTable :parentHandler="true" @triggerClick="yourMethodFoo"/>
</Your-component>
于 2019-06-21T10:43:01.870 回答