property this.$el undefined on single file component vue js

15,889

$el doesn't exist until mounted.

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

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

See the lifecycle diagram in the documentation.

Share:
15,889

Related videos on Youtube

ivanjj22
Author by

ivanjj22

Updated on June 04, 2022

Comments

  • ivanjj22
    ivanjj22 over 1 year

    I'm trying to create a global component using laravel mix with vue js, but when accessing property this.$el it's undefined. Here's my component file:

    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

    But, when the component is created as X-Template it works:

    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>
    
  • ivanjj22
    ivanjj22 over 6 years
    But it works when the component is created with X-Template, $el exists until mounted.
  • Bert
    Bert over 6 years
    @ivanjj22 No, in your X-Template example, you are using mounted.
  • pstoev
    pstoev about 2 years
    Also check your ref attribute (accessible via $ref property in the component), if you are trying to reference an element ($el) this way.