问题
i really stucked in my project. I have a site with alpine.js where i want to render data to an element
Everything is working perfect until the fact that my flatpickr is not shown up. The datepicker is working perfect. It seams, that x-html, x-text nor document.getElementById().innerHTML used in alpine.js is working ....
<div x-data="app()" x-html="modalData" x-show="isOpenModal" id="test">
only a test
<input class="picker" />
</div>
......
<script>
const fp = flatpickr(".picker", {
locale: "at",
minDate: "1930-01",
maxDate: 'today',
enableTime: true,
time_24hr: true,
minTime: "07:00",
maxTime: "20:00",
dateFormat: "d.m.Y H:i",
disableMobile: "true",
static:false,
});
function app(){
return {
isOpenModal: true,
modalData: '<input class=" form-control placeholder-primary-500 picker">',
}
}
in this very simple example 2 input field are shown up, but only the second shows the flatpickr.
Try:
- If i delete the second the first will be not working.
- x-text instead of x-html brings only the text <input ..... >
- on the other hand without alpine.js it is working
<script>
const test = document.getElementById('test').innerHTML = '<input class="picker" />';
const fp = flatpickr(".picker", {
locale: "at",
minDate: "1930-01",
maxDate: 'today',
enableTime: true,
time_24hr: true,
minTime: "07:00",
maxTime: "20:00",
dateFormat: "d.m.Y H:i",
disableMobile: "true",
static:false,
});
</script>
UPDATE 30.10.20: I simplified the code, is still not working but why ?
<div x-data="test()">
<button @click="show = true"> Klick </button>
<div x-show="show" x-model="daten" x-html="daten">
<input class="bg-green-500 picker" />
</div>
it is shown up correctly, flatpickr is initialized but the picker is not shown up.
function test() {
return {
daten:'<input class="bg-red-500 picker" />',
show: false,
}
}
such a simple code and not working :( I hope you understand my confusing special problem.
Thanks for helping,
Greets Martin
回答1:
The issue here is initializing the flatpickr
. if you add it on the init
hook of the alphine component it works perfectly. so when alphine component initializes the code segment in init
hook will be executed.
So to solve your issue,
<div x-data="app()" x-init="initFlatpickr">
<input x-ref="picker" />
</div>
and in the script tag,
<script>
function app() {
return {
initFlatpickr() {
const fp = flatpickr(this.$refs.picker, {
locale: "at",
minDate: "1930-01",
maxDate: "today",
enableTime: true,
time_24hr: true,
minTime: "07:00",
maxTime: "20:00",
dateFormat: "d.m.Y H:i",
disableMobile: "true",
static: false,
});
}
}
}
</script>
Now the initFlatpickr
function will execute when the alphine js component is initialized.
I have made use of refs
which is a helpful alternative to setting ids and using document.querySelector
all over the place.
check out the docs for more detail.
来源:https://stackoverflow.com/questions/64597995/alpine-js-flatpickr-datetimepicker-is-not-working