How to add vanilla .js to a custom Vue component

最后都变了- 提交于 2019-11-29 07:07:42

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. What you will typically make is called a wrapper component. Essentially, a Vue component that handles all the interaction with the external library. In this case you want to use Flatpickr. From the documentation, you need to use 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.

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

Here is a fiddle showing that.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!