扩展Vuetify组件

Đor*_*jić 8 vue.js vuejs2

扩展vue(vuetify)组件的最佳方法是什么v-select.

例如,我想创建<v-city></v-city>一个扩展的组件,v-select其中props加载了最小的异步项,并选择了一个项.

我已经开始了 template

<template>
    <v-select
        :items="items"
        v-model="item"
        required
        return-object
        autocomplete
        item-text="name"
        item-value="id"
    ></v-select>
</template>
Run Code Online (Sandbox Code Playgroud)

script

<script>
    export default {
        name: 'v-city',
        data()
        {
            return {
                item: null,
                items: [],
                disabled: true
            };
        },
        created()
        {
            this.$http({
                method: 'GET',
                url: '/api.cities'
            })
                .then(response => this.items = response.data)
                .catch(console.warn);
        },
        methods: {},
        watch: {
            item(nv)
            {
                this.$emit('update', nv.id);
            }
        }
    };
</script>
Run Code Online (Sandbox Code Playgroud)

用法: <v-city @update="local.city = arguments[0]"></v-city>

我要归档的是: <v-city v-model="local.city" label="Select city"></v-city>

Kae*_*har 8

“扩展”任何组件的最佳方法是将其包装。

<template>
  <v-select v-bind="$attrs" v-on="$listeners">
    <!-- pass through scoped slots -->
    <template v-for="(_, name) in $scopedSlots" v-slot:[name]="data">
      <slot :name="name" v-bind="data" />
    </template>

    <!-- pass through normal slots -->
    <template v-for="(_, name) in $slots" v-slot:[name]>
      <slot :name="name" />
    </template>
  </v-select>
</template>
Run Code Online (Sandbox Code Playgroud)

属性默认值可以直接添加内联:

<v-select open-on-clear v-bind="$attrs" v-on="$listeners">
Run Code Online (Sandbox Code Playgroud)

某些组件(例如 v-checkbox)还使用模型的非默认 prop 和事件,因此您可能还需要对其进行设置才能v-model正常工作:

<script>
  export default {
    model: {
      // These are the default values
      prop: 'value',
      event: 'input'
    }
  }
</script>
Run Code Online (Sandbox Code Playgroud)

您可能会发现其他一些也可以使用的答案extends

<script>
  import { VSelect } from 'vuetify/lib'
  export default {
    extends: VSelect,
  }
</script>
Run Code Online (Sandbox Code Playgroud)

这有时起作用,例如,如果您只想覆盖组件的方法之一。但不要extends与结合使用<template>,这会覆盖渲染函数并且几乎总是会破坏组件。


v3 类似,但 $listeners 和 $scopedSlots 不再存在,并且 v-model 始终是modelValue

<template>
  <v-select v-bind="$attrs">
    <template v-for="(_, name) in $slots" v-slot:[name]="data">
      <slot :name="name" v-bind="data" />
    </template>
  </v-select>
</template>
Run Code Online (Sandbox Code Playgroud)


小智 0

您可以将 v-select 组件与 v-city 一起包装,并通过 v-city 组件传递 props。如果需要的话,您可以全局定义组件