vue.js - 扩展 Vuetify 组件

标签 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>

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>

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

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

最佳答案

“扩展”任何组件的最佳方式是包装它。

<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>

Prop 默认值可以内联添加:

<v-select open-on-clear v-bind="$attrs" v-on="$listeners">

一些组件(例如 v-checkbox)也使用模型的非默认属性和事件,因此您可能还需要为 v-model 设置它。正常工作:

<script>
  export default {
    model: {
      // These are the default values
      prop: 'value',
      event: 'input'
    }
  }
</script>

您可能会发现一些其他答案说使用 extends还有:

<script>
  import { VSelect } from 'vuetify/lib'
  export default {
    extends: VSelect,
  }
</script>

有时 可以工作,例如,如果您只想重写组件的一个方法。不要合并 extends<template>不过,这会覆盖渲染函数并且几乎总是会破坏组件。

关于vue.js - 扩展 Vuetify 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48310902/

相关文章:

javascript - 导轨+Vue : Accessing instance variable

vue.js - vue 属性作为没有值的 prop 名称

javascript - Vue 对象未使用 axios POST 请求更新

vuejs2 - Vue中子组件向父组件传递数据

javascript - 如何导航到 Framework7 + Vue 应用程序中的路线?

html - 输入元素(由vuetify生成)不会中断长文本的行

javascript - Vue JS - 响应式(Reactive)电话号码格式

javascript - 如何在 vue 组件中使用 Maatwebsite 导入 excel 文件?

javascript - 基于条件的 VueJS HTML 元素类型

javascript - Laravel 5.2 - vue 集成