简体   繁体   English

如何将 vanilla .js 添加到自定义 Vue 组件

[英]How to add vanilla .js to a custom Vue component

I'm trying to add a simple date-picker to a custom vue component.我正在尝试向自定义 vue 组件添加一个简单的日期选择器 I'm not using webpack so I want to avoid ready made .vue components and I rather understand how to add simple javascript to vue.我没有使用 webpack,所以我想避免使用现成的.vue组件,我更了解如何将简单的 javascript 添加到 vue。

I'm following this official vue tutorial我正在关注这个官方的 vue 教程

I've also seen this codepen but I can't manage to make the date picker appear.我也看过这个 codepen ,但我无法让日期选择器出现。

This is my jsfiddle :这是我的jsfiddle

Html: html:

<div class="app">
  <datepicker id='date-elem'></datepicker>
</div>

app.js:应用程序.js:

Vue.component('date-picker', {
  extends: Flatpickr,
  mounted () {
    this.Flatpickr(date-elem, {})}
})

How can I easily integrate vanilla js in a Vue component without the need of .vue files, webpack etc?如何在不需要 .vue 文件、webpack 等的情况下轻松地将 vanilla js 集成到 Vue 组件中?

So you have a few misconceptions here.所以你在这里有一些误解。 To make this a component (a very basic component), this is how you might do it.为了使它成为一个组件(一个非常基本的组件),您可以这样做。

In Vue, you're not going to typically extend an external Javascript library.在 Vue 中,您通常不会扩展外部 Javascript 库。 What you will typically make is called a wrapper component.您通常会制作的称为包装器组件。 Essentially, a Vue component that handles all the interaction with the external library.本质上,一个 Vue 组件处理与外部库的所有交互。 In this case you want to use Flatpickr.在这种情况下,您想使用 Flatpickr。 From the documentation , you need to use new Flatpickr(element, options) .文档中,您需要使用new Flatpickr(element, options) So we can do that in the mounted event, passing this.$el which will point to the root Vue component element.所以我们可以在mounted事件中这样做,传递this.$el指向根 Vue 组件元素。

Vue.component('date-picker', {
    template: "<input type='text'>",
    mounted () {
        new Flatpickr(this.$el, {})
    }
})

Here is your updated fiddle .这是您更新的小提琴

But this component doesn't do very much.但是这个组件并没有做太多。 It just allows you to pick a date.它只允许您选择一个日期。 To allow that date to be used outside the component, we want to extend it to support v-model .为了允许在组件外部使用该日期,我们希望扩展它以支持v-model Here's how you might do that.以下是您可以这样做的方法。

Vue.component('date-picker', {
    props:["value"],
    data(){
        return {
            selectedDate: this.value
        }
    },
    template: "<input type='text' v-model='selectedDate' @input='onInput'>",
    methods:{
        onInput(){
            this.$emit('input', this.selectedDate)
        }
    },
    mounted () {
        new Flatpickr(this.$el, {})
    }
})

Now, you can use it like this.现在,您可以像这样使用它。

<date-picker v-model="selectedDate"></date-picker>

And selectedDate will receive the date you pick. selectedDate 将收到您选择的日期。

Here is a fiddle showing that.这是一个显示这一点的小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM