Nuxt 异步请求动画实现方法:插件和中间件
在 Nuxt 中,可以使用插件和中间件来实现异步请求动画。
- 插件
可以使用 Vue 插件来实现异步请求动画,具体步骤如下:
1.1 在 plugins 目录下新建一个文件,例如 loading.js。
1.2 在 loading.js 中定义一个 Vue 插件:
import Vue from 'vue'
Vue.use({
install: function (Vue) {
Vue.prototype.$loading = {
show: function () {
// 显示加载动画
},
hide: function () {
// 隐藏加载动画
}
}
}
})
1.3 在 nuxt.config.js 中引入该插件:
plugins: [
{ src: '~/plugins/loading.js', ssr: false }
]
1.4 在组件中使用该插件:
mounted () {
this.$loading.show()
// 异步请求
this.$http.get('/api/data').then(response => {
this.data = response.data
this.$loading.hide()
})
}
- 中间件
可以使用 Nuxt 的中间件来实现异步请求动画,具体步骤如下:
2.1 在 middleware 目录下新建一个文件,例如 loading.js。
2.2 在 loading.js 中定义一个中间件:
export default function ({ store, route, redirect }) {
store.commit('loading/show')
return new Promise((resolve, reject) => {
// 在异步请求完成后隐藏加载动画
resolve()
})
}
2.3 在 nuxt.config.js 中配置该中间件:
router: {
middleware: 'loading'
}
2.4 在 Vuex 中定义相应的状态和 mutation:
state: {
loading: false
},
mutations: {
show (state) {
state.loading = true
},
hide (state) {
state.loading = false
}
}
2.5 在组件中使用该状态:
<template>
<div v-if="$store.state.loading">加载中</div>
<div v-else>内容</div>
</template>
原文地址: https://www.cveoy.top/t/topic/lU6n 著作权归作者所有。请勿转载和采集!