将属性默认值注入 3rd 方 Vue 组件

编程入门 行业动态 更新时间:2024-10-28 08:19:39
本文介绍了将属性默认值注入 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")

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

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

这是我尝试过的:

  • 扩展 Datepicket 组件的自定义组件:没有那么好,因为我需要定义一个包含原始日期选择器组件的模板.这意味着一个多余的包装组件
  • 插件?我只能将属性注入到全局 Vue 实例中.(对 Vue 很陌生)
  • mixin 不适用,因为我需要更改 3rd 方组件
推荐答案

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

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

例如

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

演示:jsfiddle/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" } } };

演示:codesandbox.io/s/9kn29053r

更多推荐

将属性默认值注入 3rd 方 Vue 组件

本文发布于:2023-11-08 13:13:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569473.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:默认值   组件   属性   Vue

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!