【问题标题】:How to run a js code after vuejs render html changesvuejs渲染html更改后如何运行js代码
【发布时间】:2018-10-02 20:40:10
【问题描述】:

我正在使用 jquery 日期选择器工具。但它在 v-if 内。如果我编写此代码,当我打开和关闭它时它不起作用。

showdatepicker:function(){
    this.datepicker= true;
    $(".jquery-date-picker").datepicker();
}

因为当 $(".jquery-date-picker").datepicker();运行 vue 仍然没有呈现 html 并添加了我的 datepicker 输入。但如果将其更改为:

showdatepicker:function(){
    this.datepicker= true;
    setTimeout(function(){$(".jquery-date-picker").datepicker();},0);
}

它有效。因为在 html 渲染之后运行它。

我的问题:在 html 渲染之后,setTimeout 是一种有保证的方法吗? vuejs 中是否有建议的方法来做到这一点。我在 google 和 stackoverflow 搜索中找不到任何答案。

【问题讨论】:

    标签: vuejs2


    【解决方案1】:

    您可以使用nextTick,它将在下一个 DOM 更新周期后调用一个函数。

    this.datepicker = true;
    
    Vue.nextTick(function () {
      $(".jquery-date-picker").datepicker();
    })
    

    这是文档中的页面VueJS Docs

    【讨论】:

      【解决方案2】:

      Vue 具有触发器,在您的情况下,可以使用 mounted() 函数。本文介绍了如何使用它以及整个 Vue hook 时间线:https://alligator.io/vuejs/component-lifecycle/

      stackoverflow 解释:Vue JS mounted()

      【讨论】:

        猜你喜欢
        • 2013-05-31
        • 1970-01-01
        • 1970-01-01
        • 2012-08-31
        • 2017-02-16
        • 2017-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多