【问题标题】:Vue component gets recreated after created methodVue 组件在创建方法后重新创建
【发布时间】:2021-09-18 17:40:00
【问题描述】:

当图像对话框创建时,我尝试计算图像的边距以将其显示在页面的中心。我在组件的 created 方法中计算边距,当我调试时,我看到它在我的 jquery 边距设置方法之后正确定位。但是当我继续调试时,组件以某种方式重新渲染而没有进入 created 方法,并且图像的边距没有设置。当我尝试在 created 方法中设置一些变量并且它总是重新渲染而不进入 created 块时,我一直遇到这种情况。有什么办法可以防止这种情况发生吗?真的很烦。

这是我创建的块:

async created() {
    let self = this;

    $('.vodal.image-dialog').css('cursor', 'wait');

    $('.vodal.image-dialog').css('cursor', 'default');
    var margin = $(window).width() / 2 - $(".vodal.image-dialog .pop-up img").width() / 2;
    $(".vodal.image-dialog img").css('margin-left', margin);
    $(".vodal.image-dialog .pop-up img").show();

  },

更新:

我通过简单地使用 v-bind:style 提供 margin 属性并从这样的计算属性中获取它来解决这个问题:

<img v-if="isEntitySaved()" v-bind:style="{'margin-left': margin + 'px'}"
      v-bind:src="image" class="blurred"/>
...
computed: {
    margin: function() {
      var imgClass = ''
      if(this.source == 'detail-main')
        imgClass = ".vodal.image-dialog .pop-up .main-image img"
      else
        imgClass = ".vodal.image-dialog .pop-up .side-image img"

      return $(window).width() / 2 - $(".vodal.image-dialog .pop-up ." + this.source + " img").width() / 2
    }
  }

但问题仍然存在,在另一个组件中,我最初的模板样式为“显示:无”。单击某个按钮后,我想显示它,因此我在 createdupdated 方法中将其样式设置为“显示:块”,但在$.show 方法在创建块的和处,但组件被重新渲染并消失,而不进入创建或更新的块。我该如何解决这个问题?

【问题讨论】:

  • 哎呀,为什么你的 Vue 应用程序中有 jQuery?

标签: javascript vue.js vuejs2 vue-component


【解决方案1】:

created 钩子只被调用一次,您需要利用 updated 钩子。

export default {
  created() {
    this.updateStyle();
  },
  updated() {
    this.updateStyle();
  },
  methods: {
    updateStyle() {
      let self = this;

      $(".vodal.image-dialog").css("cursor", "wait");

      $(".vodal.image-dialog").css("cursor", "default");
      var margin =
        $(window).width() / 2 -
        $(".vodal.image-dialog .pop-up img").width() / 2;
      $(".vodal.image-dialog img").css("margin-left", margin);
      $(".vodal.image-dialog .pop-up img").show();
    },
  },
};

更新

因为你在 Vue 应用中使用了太多的 jQuery。

最快解决问题的方法就是像这样强制重新渲染

export default {
  data() {
    return {
      count: 0,
    };
  },
  updated() {
    // updated will guarantee to be called if you modify this.count
  },
  methods: {
    doSomething() {
      // do what ever you want
      // .......
      // At the end, make sure to call this
      this.count++;
    },
  },
};

【讨论】:

  • 我更新了问题,你能检查一下吗?
  • 我已经更新了答案。
猜你喜欢
  • 2019-07-25
  • 1970-01-01
  • 2020-03-24
  • 2019-06-18
  • 2019-12-24
  • 2018-09-06
  • 1970-01-01
  • 2019-10-14
  • 1970-01-01
相关资源
最近更新 更多