I wrote a small code with Laravel, Vue and JQuery, which works fine. Now I want to remove JQuery and run all with Vue and Axios.
Here's my template:
<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>
Following code actually works and I can render what I get from AJAX. I know how to apply Axios, no problem.
The point I'm confused about: How can I ensure $(document).ready(
functionality with 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, $);
@undefined, this is almost the same as $(document).
Although you can replace jQuery with Vue, you'll need to change your mindset about how to solve Web development problems.
no. if you've placed all your scripts right before the </body> closing tag, you've done the exact same thing. Additionally, if the script doesn't need to access the DOM, it won't matter where it's loaded beyond possible dependencies on other scripts.
The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.
Similar approach, but without JQuery and just using Javascript:
mounted() {
document.addEventListener('DOMContentLoaded', function () {
// INSERT CODE HERE
});
}
The recommended way by vue to do this is using mounted().
mounted: function () {
this.$nextTick(function () {
// Code that will run only after the
// entire view has been rendered
})
}
Check: https://v2.vuejs.org/v2/api/#mounted
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With