我尝试使用带有vue js的laravel mix创建一个全局组件,但是当访问属性this.$el
时,它未定义。这是我的组件文件:
Datepicker.vue
<template>
<input
type="text"
:name="name"
:class="myclass"
:placeholder="placeholder"
:value="value" />
</template>
<script>
export default {
props: ['myclass','name','placeholder','value'],
data () {
return {
}
},
created () {
console.log("this.$el", this.$el); //undefined
console.log("this", this); //$el is defined
var vm = this;
var options = {
"locale": "es",
"onChange": function(selectedDates, dateStr, instance) {
vm.$emit('input', dateStr);
}
};
$(this.$el)
// init
.flatpickr(options);
},
destroyed(){
console.log("destroyed");
}
}
</script>
但是,当组件创建为X-Template时,它可以工作:
client.js
Vue.component('date-picker', {
props: ['myclass','name','placeholder','value'],
template: '#datepicker-template',
mounted: function () {
var vm = this;
var options = {
"locale": "es",
"onChange": function(selectedDates, dateStr, instance) {
vm.$emit('input', dateStr);
}
};
$(this.$el)
// init
.flatpickr(options);
},
destroyed: function () {
console.log("destroyed");
}
});
create.blade.php
<script type="text/x-template" id="datepicker-template">
<input
type="text"
:name="name"
:class="myclass"
:placeholder="placeholder" />
</script>
答案 0 :(得分:6)
$el
在mounted
之前不存在。
mounted() {
var vm = this;
var options = {
"locale": "es",
"onChange": function(selectedDates, dateStr, instance) {
vm.$emit('input', dateStr);
}
};
$(this.$el)
// init
.flatpickr(options);
},
请参阅文档中的lifecycle diagram。