Примерно так,
Первый способ - vuex
index.html:
<div class="preloader"></div>
<style>.preloader{/* preloader styles */}</style>
<div id="app"></div>
App.vue:
<template>
<div>
<router-view />
</div>
</template>
<script>
import { mapState } from 'vuex';
const preloader = document.querySelector('.preloader');
export default {
computed: {
...mapState('app', ['loading']),
},
watch: {
loading: {
handler(val) {
preloader.style.display = val ? '' : 'none';
},
immediate: true,
},
},
};
</script>
store/modules/app.js:
import Vue from 'vue';
export const state = {
loading: true,
};
export const mutations = {
SET_LOADING(state, loading) {
state.loading = loading;
},
};
export const actions = {
setLoading({ commit }, loading) {
commit('SET_LOADING', loading);
},
};
YouPage.vue:
<script>
import axios from 'axios';
import { mapActions } from 'vuex';
export default {
methods: {
...mapActions('app', ['setLoading']),
},
created() {
axios.get('/api/page-data').then(res => {
console.dir(res);
}).catch(err => {
console.dir(err);
}).finally(() => this.setLoading(false));
}
};
</script>
Если vuex не используете или нет нужды, можно обойтись событиями:
index.html:
<div class="preloader"></div>
<style>.preloader{/* preloader styles */}</style>
<div id="app"></div>
App.vue:
<template>
<div>
<router-view />
</div>
</template>
<script>
const preloader = document.querySelector('.preloader');
export default {
data() {
return {
loading: true,
};
},
methods: {
setLoading(loading) {
this.loading = loading;
preloader.style.display = loading ? '' : 'none';
},
},
mounted() {
this.$on('set-loading', this.setLoading);
},
destroyed() {
this.$off('set-loading', this.setLoading);
}
};
</script>
YouPage.vue:
<script>
import axios from 'axios';
export default {
created() {
axios.get('/api/page-data').then(res => {
console.dir(res);
}).catch(err => {
console.dir(err);
}).finally(() => this.$root.$emit('set-loading', false));
}
};
</script>