像 $(document).ready( 和 Vue.js 的功能

新手上路,请多包涵

我用 Laravel、Vue 和 JQuery 写了一小段代码,效果很好。现在我想 删除 JQuery 并使用 Vue 和 Axios 运行所有。

这是我的模板:

  <ul id="product_list" class="vue-list-wrapper list-wrapper" data-rest="{{ route('rest_get_products', ["id"=>$product_type_id]) }}" data-pagination="0">
    <li v-for="item in items">
        <div class="item-name item-section">@{{ item.name }}</div>
        ...bla bla...
    </li>
</ul>

以下代码确实有效,我可以呈现从 AJAX 获得的内容。我知道如何应用Axios,没问题。

我感到困惑的一点是: 如何确保 $(document).ready( Vue 的功能

 (function(){
"use strict";

function init_vue_list(){

    var vue_list_handler = new Vue({
        el: '.vue-list-wrapper',
        data: {
            items: []
        },
        mounted: function (event) {
            var self = this;
            var ajax_url = this.$el.getAttribute('data-rest');

            $.ajax({ // No problem to convert this to Axios.
                url: ajax_url,
                method: 'GET',
                success: function (data) {
                    self.items = data;
                },
                error: function (error) {
                    console.log(error);
                }
            });
        },
        methods:{
            open_production:function(event){

            }
        }
    });

}

$(document).ready( // I'm confused how I can replace this with Vue.
    function(){
        if($('.vue-list-wrapper').length > 0) {
            init_vue_list();
        }
    }
);

})(document, $);

原文由 tolga 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.9k
2 个回答

vue 推荐的方法是使用 mounted()

 mounted: function () {
  this.$nextTick(function () {
    // Code that will run only after the
    // entire view has been rendered
  })
}

检查: https ://v2.vuejs.org/v2/api/#mounted

原文由 Koustav Ray 发布,翻译遵循 CC BY-SA 4.0 许可协议

类似的方法,但没有 JQuery,只使用 Javascript:

 mounted() {
    document.addEventListener('DOMContentLoaded', function () {
        // INSERT CODE HERE
    });
}

原文由 allenski 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏