vueelementui搭建项目

该文章详细介绍了如何在Vue项目中集成ElementUI库进行UI设计,使用vue-router搭建路由系统,以及结合axios处理HTTP请求。文中还涉及到请求拦截器的设置,用于处理错误和令牌验证。

https://blog.youkuaiyun.com/weixin_44882488/article/details/124220864

vue create vue01

https://blog.youkuaiyun.com/weixin_56800176/article/details/127564088

npm i element-ui -S

main.js中写入以下内容:

import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App.vue';
Vue.use(ElementUI);
new Vue({
 el: '#app',
 render: h => h(App)
});

npm i vue-router@3.5.3

首先在src里面创建
router的目录,在router目录里面创建一个index.js文件
views目录 mian.vue

import Vue from 'vue'; //导入vue
import Router from 'vue-router'; /* 导入路由 */
import Login from '@/views/HelloWorld.vue'; /* 导入其他组件 */
import Main from '@/views/HelloWorld.vue'; 
Vue.use(Router)
/* 定义组件路由 */
var router = new Router({
	routes: [{
			path: '/', //ip:端口访问时 默认显示组件
			component: Login
		},
		{
			path: '/login', //组件地址
			component: Login
		},
		{
			path: '/main',
			component: Main
		}
 
	]
});
export default router

main.js

import Vue from 'vue'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

import router from './router/index.js'
import App from './App.vue'
Vue.use(ElementUI);
Vue.use(router)

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
  router,
}).$mount('#app')

app.vue

<template>
  <div id="app">
    <!-- router-view就是用来显示不同组件的 -->
		<router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'App',
}
</script>

<style>
</style>

npm install axios

utils目录 request.js

import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['X-Token'] = getToken()
      if (!config.data) config.data = {}
      if (!config.params) config.params = {}
      config.params['token'] = getToken()
      config.params['_t'] = new Date().getTime()
      config.method === 'post' ? config.data['token'] = getToken() : config.params['token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (res.code && res.code !== 0) {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      // console.log(res)
      if (res.code === 401) { // 401, token失效
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      }
      // return Promise.reject(new Error(res.msg || 'Error'))
      return { msg: 'Error' }
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

api 目录

api.js

import request from '@/utils/request'

export function getRoles(obj) {
  return request({
    url: 'pm/file/upload',
    method: 'post',
    data: obj
  })
}

.vue

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <p>
      11111For a guide and recipes on how to configure / customize this project,<br>
      check out the
    </p> 
  </div>
</template>

<script>
import { getRoles } from '@/api/api'
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data() {
    return {
      pageIndex: false,
      pageSize: false,
      dataList: [],
    }
  },
  created() {
    console.log(12312)
    this.getDataList()
  },
  methods: {
    // 获取数据列表
  getDataList() {
      getRoles({
        'page': this.pageIndex,
        'limit': this.pageSize,
      }).then((data) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
      })
    },
  },
  
}
</script>

<style scoped>
</style>

搭建 Vue + ElementUI 项目可按以下步骤进行: ### 技术选型 - Vue.js 版本推荐 Vue 2.x,其与 ElementUI 更兼容且文档丰富。 - UI 框架选用 ElementUI,该框架组件丰富,适合后台管理。 - 脚手架工具使用 Vue CLI,这是官方推荐的工具,可快速搭建项目结构。 - 构建工具采用 Webpack,它由 Vue CLI 内置。 - 开发语言可选择 JavaScript,若熟练也可用 TypeScript [^1]。 ### 使用 Vue CLI 创建项目 Vue CLI 提供标准命令用于快速搭建基于 Webpack、Babel、Vue Router 等的现代前端开发环境。使用此命令会自动配置好开发服务器、构建工具、ESLint、TypeScript 支持等。还能选择默认配置或手动选择功能,如 Babel、Router、Vuex、CSS 预处理器等,保证项目结构标准化,方便后续维护和部署 [^2]。 ### 安装 Element UI 可使用命令 `npm i element-ui -S` 进行安装,其官网为 https://element.eleme.cn/#/zh-CN 。同时,需在 `router` 中的 `index.js` 添加 `import ElementUI from 'element-ui'` 和 `Vue.use(ElementUI)`。另外,还可安装 sass,命令为 `npm i sass-loader node-sass -S` [^3]。 ### 修改 main.js 在 `main.js` 中进行如下修改: ```javascript // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' Vue.use(ElementUI); Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, components: { App }, template: '<App/>' }) ``` 这样能使项目正确引入并使用 ElementUI [^4]。 ### 修改 prefix 和 cache 路径(可选) 若有需求,可打开终端(命令行窗口),运行以下命令来修改 `prefix` 和 `cache` 路径: ```bash npm config set prefix "F:\nodeResp\npm" npm config set cache "F:\nodeResp\cache" ``` [^5]
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值