问题描述
我正在尝试向自定义vue组件添加一个简单的。我没有使用webpack所以我想避免现成的 .vue
组件,而我更了解如何添加简单的javascript到vue。
I'm trying to add a simple date-picker to a custom vue component. 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.
我正在关注
我也见过但我无法设置日期选择器。
I've also seen this codepen but I can't manage to make the date picker appear.
这是我的:
Html:
<div class="app">
<datepicker id='date-elem'></datepicker>
</div>
app.js:
Vue.component('date-picker', {
extends: Flatpickr,
mounted () {
this.Flatpickr(date-elem, {})}
})
如何在Vue组件中轻松集成vanilla js而无需.vue文件,webpack等?
How can I easily integrate vanilla js in a Vue component without the need of .vue files, webpack etc?
推荐答案
所以你在这里有一些误解。要使它成为一个组件(一个非常基本的组件),你可以这样做。
So you have a few misconceptions here. To make this a component (a very basic component), this is how you might do it.
在Vue中,你通常不会扩展外部Javascript库。您通常会将其称为包装器组件。本质上,Vue组件处理与外部库的所有交互。在这种情况下,您想使用Flatpickr。从中,您需要使用新的Flatpickr(元素) ,选项)
。所以我们可以在挂载的
事件中执行此操作,传递这个。$ el
,它将指向根Vue组件元素。
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, {})
}
})
这是您更新的。
但是这个组件做的不多。它只允许你选择一个日期。要允许该日期在组件之外,我们希望将其扩展为支持 v-model
。以下是你可以这样做的方法。
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>
且selectedDate将收到您选择的日期。
And selectedDate will receive the date you pick.
显示了这一点。
这篇关于如何将vanilla .js添加到自定义Vue组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!