Answer the question
In order to leave comments, you need to log in
How to make JS method execute after full page rendering in Vue.js?
What do I do?
1. Ajax request to the server through the axios library. I get, for example, a list of machines (id -> name).
2. In a cycle I build option for select.
3. I apply bootstrap-select to this select. It is needed to customize select:
What's the problem?
The selectpicker JS script doesn't have time to wait for Vue.js to render the select-> option, assuming there are no elements there.
Simplified code looks like this:
<template>
<div>
<select name="cars" class="selectpicker">
/* 2. Vue.js, получив данные, начал рендерить option */
<option v-for="(val, key) in cars" :key="key" :value="key">{{val}}</option>
</select>
</div>
</template>
<script>
export default {
data() {
return {
cars: []
}
},
mounted() {
axios.get('/info/car')
.then((result) => {
this.cars = result.data; /* 1. Получили данные от сервера и записали в переменную. */
$('.selectpicker').selectpicker(); /* 3. Иногда не успевает дождаться рендеринга и
в select не отображает элементы, ибо vue.js их еще не создал. */
});
}
}
</script>
<template>
<div>
<select name="cars" class="selectpicker" id="carList">
/* Использует computed listCar */
<option v-for="(val, key) in listCar" :key="key" :value="key">{{val}}</option>
</select>
</div>
</template>
computed: {
...mapState(['list']), // Получили
listCar() {
return this.list.cars;
}
},
watch: {
listCar() { // Отслеживает, чтобы список с сервера уже был загружен.
this.$nextTick(function () { // Ждем пока отрендерит.
$('#carList').selectpicker(); // Применяет selectpicker
})
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question