【问题标题】:property this.$el undefined on single file component vue js单个文件组件vue js上的属性this.$el未定义
【发布时间】:2018-01-06 05:31:03
【问题描述】:

我正在尝试使用 laravel mix 和 vue js 创建一个全局组件,但是在访问属性 this.$el 时它是未定义的。这是我的组件文件:

日期选择器.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>

【问题讨论】:

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


    【解决方案1】:

    $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

    【讨论】:

    • 但是当使用X-Template创建组件时它可以工作,$el在挂载之前一直存在。
    • @ivanjj22 不,在您的 X-Template 示例中,您使用的是 mounted
    • 如果您尝试以这种方式引用元素 ($el),还请检查您的 ref 属性(可通过组件中的 $ref 属性访问)。
    猜你喜欢
    • 2018-01-27
    • 2019-09-08
    • 2021-03-18
    • 2021-05-26
    • 1970-01-01
    • 2020-03-24
    • 1970-01-01
    • 2020-11-22
    • 2021-09-14
    相关资源
    最近更新 更多