返回

Vue全局loading以及错误提示

前端

全局loading

  1. 安装vue-loading-overlay组件库:
npm install vue-loading-overlay --save
  1. 在main.js文件中导入组件库:
import Vue from 'vue'
import VueLoading from 'vue-loading-overlay'

Vue.use(VueLoading)
  1. 在根组件中创建一个全局变量来控制loading状态:
export default {
  data() {
    return {
      loading: false
    }
  },
  methods: {
    showLoading() {
      this.loading = true
    },
    hideLoading() {
      this.loading = false
    }
  }
}
  1. 在需要显示loading的组件中使用v-if指令来控制loading状态:
<template>
  <div v-if="loading">
    <loading />
  </div>
  <!-- 其他内容 -->
</template>

<script>
export default {
  data() {
    return {
      loading: false
    }
  },
  methods: {
    showLoading() {
      this.loading = true
    },
    hideLoading() {
      this.loading = false
    }
  }
}
</script>

错误提示

  1. 使用axios库来发送HTTP请求:
npm install axios --save
  1. 在main.js文件中导入axios库:
import Vue from 'vue'
import axios from 'axios'

Vue.use(axios)
  1. 在根组件中创建一个全局变量来控制错误提示:
export default {
  data() {
    return {
      error: null
    }
  },
  methods: {
    showError(error) {
      this.error = error
    },
    clearError() {
      this.error = null
    }
  }
}
  1. 在需要显示错误提示的组件中使用v-if指令来控制错误提示:
<template>
  <div v-if="error">
    <error-message :error="error" />
  </div>
  <!-- 其他内容 -->
</template>

<script>
export default {
  data() {
    return {
      error: null
    }
  },
  methods: {
    showError(error) {
      this.error = error
    },
    clearError() {
      this.error = null
    }
  }
}
</script>

总结

通过使用Vuex状态管理、自定义组件和动画,我们可以轻松地为Vue应用程序添加全局loading和错误提示功能。这些功能可以显著提升用户体验,并使我们的应用程序更加健壮可靠。