将属性默认值注入到 3rd 方 Vue 组件中 [英] Injecting property defaults into 3rd party Vue component

查看:26
本文介绍了将属性默认值注入到 3rd 方 Vue 组件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的项目中使用了一个日期选择器组件.基本用法如下:

I am using a datepicker component in my project. Basic usage would be like this:

date-picker(language="fr" v-model="date")

有几个属性会在每次我们需要使用日期选择器时重复:例如 language.

There are several attributes which will get repeated each time we need to use a date picker: language for instance.

所以我希望能够在需要日期选择器时简单地做到这一点.

So I would like to be able to simply do that when a date picker is needed.

date-picker(v-model="date")

对于第三方库的 language 属性,这将默认为 fr.

And that would default to fr for the language property of the 3rd party library.

这是我尝试过的:

  • 扩展 Datepicket 组件的自定义组件:不是很好,因为我需要定义一个包含原始日期选择器组件的模板.这转化为一个多余的包装器组件
  • 插件?我只能向全局 Vue 实例注入属性.(Vue 的新手)
  • Mixin 不适用,因为我需要更改第 3 方组件

推荐答案

不确定您是如何扩展组件的.但这应该够优雅了吧?

Not sure how you extended the component. But this should be elegant enough?

例如

Vue.component("extended-datepicker", {
  extends: vuejsDatepicker,
  props: {
    format: {
      default: "yyyy MMM(MM) dd"
    },
    language: {
        default: fr
    }
  }
});

演示:https://jsfiddle.net/jacobgoh101/5917nqv8/2/

更新单个文件组件需要提供模板标签"的问题

Update for the problem where "single file components are required to provide a template tag"

Vue 组件本质上是一个具有某些属性的 JavaScript 对象.

A Vue component is essentially a JavaScript object with certain properties.

您并不总是需要使用 .vue 单文件组件.在这种情况下,您可以创建一个导出对象的 .js 文件.

You don't always need to use .vue single file component. In this case, you can just create a .js file that export an object.

例如这个 ExtendedDatepicker.js 将是一个有效的 Vue 组件

For e.g. this ExtendedDatepicker.js would be a valid Vue component

import Datepicker from "vuejs-datepicker";

export default {
  extends: Datepicker,
  props: {
    format: {
      default: "yyyy MMM(MM) dd"
    }
  }
};

演示:https://codesandbox.io/s/9kn29053r

这篇关于将属性默认值注入到 3rd 方 Vue 组件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆