属性这个。$ el undefined在单个文件组件vue js上

时间:2017-07-30 16:58:12

标签: javascript vue.js vuejs2 vue-component laravel-mix

我尝试使用带有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>

Console

但是,当组件创建为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>

1 个答案:

答案 0 :(得分:6)

$elmounted之前不存在。

mounted() {
  var vm = this;
  var options = {
      "locale": "es",        
      "onChange": function(selectedDates, dateStr, instance) {
          vm.$emit('input', dateStr);
      }
    };

  $(this.$el)
    // init
    .flatpickr(options);      
},

请参阅文档中的lifecycle diagram