【不断更新】Vue-element-admin UI 学习日记

生命周期

create()

  • 页面一开始就需要加载的数据,不需要任何按钮触发
  • 比如getlists等

数据传输

Get后端数据

  • get只允许query参数或者无参数
  • 你的js文件名如report.js中写入接口函数(你需要应用的接口都分类单独写js文件)
export function getReportList() {
  return request({
    url: '/admin-agent/valuation-report',
    method: 'get',
 
  })
}
  • 在index.vue中导入函数
import { 函数名如getReportList } from '@/api/你的js文件名如report'
  • 在methods中注册方法
  getList() {
        this.listLoading = true
        getReportList().then(response => {
          this.list = response.data.data
          this.listLoading = false
        })
      },
  • 此时成功得到后端数据了,让我们看看requst.js如何封装axios,这个request就是上文getReportList()的返回值,他可以灵活地更改参数,比如
import axios from 'axios'
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: 15000 // request timeout
})

// request interceptor 作为token检查
service.interceptors.request.use(
  config => {
    // do something before request is sent
    const token = getToken()
    if (token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
  • 首先axios的实例源码如下
export interface AxiosInstance {
  (config: AxiosRequestConfig): AxiosPromise;
  (url: string, config?: AxiosRequestConfig): AxiosPromise;
  defaults: AxiosRequestConfig;
  interceptors: {
    request: AxiosInterceptorManager<AxiosRequestConfig>;
    response: AxiosInterceptorManager<AxiosResponse>;
  };
  request<T = any>(config: AxiosRequestConfig): AxiosPromise<T>;
  get<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>;
  delete(url: string, config?: AxiosRequestConfig): AxiosPromise;
  head(url: string, config?: AxiosRequestConfig): AxiosPromise;
  post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>;
  put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>;
  patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>;
}
  • 可见一个axios create 会有url,两个拦截器,request以及各种方法名methods
export interface AxiosStatic extends AxiosInstance {
  create(config?: AxiosRequestConfig): AxiosInstance;
  Cancel: CancelStatic;
  CancelToken: CancelTokenStatic;
  isCancel(value: any): boolean;
  all<T>(values: (T | Promise<T>)[]): Promise<T[]>;
  spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
}
  • 回到create函数,我们发现他属于AxiosStatic接口,而AxiosStatic继承AxiosInstance;冒号赋值表示,create根据 config 或者 AxiosRequestConfig参数创建实例AxiosInstance
  • 看看这些config包括什么:更多的,可选的参数,因此,request内的键值对远远不止上述例子中那么简单,可以按需使用
export interface AxiosRequestConfig {
  url?: string;
  method?: string;
  baseURL?: string;
  transformRequest?: AxiosTransformer | AxiosTransformer[];
  transformResponse?: AxiosTransformer | AxiosTransformer[];
  headers?: any;
  params?: any;
  paramsSerializer?: (params: any) => string;
  data?: any;
  timeout?: number;
  withCredentials?: boolean;
  adapter?: AxiosAdapter;
  auth?: AxiosBasicCredentials;
  responseType?: string;
  xsrfCookieName?: string;
  xsrfHeaderName?: string;
  onUploadProgress?: (progressEvent: any) => void;
  onDownloadProgress?: (progressEvent: any) => void;
  maxContentLength?: number;
  validateStatus?: (status: number) => boolean;
  maxRedirects?: number;
  httpAgent?: any;
  httpsAgent?: any;
  proxy?: AxiosProxyConfig | false;
  cancelToken?: CancelToken;
}
  • 然后我们已经把得到的request(也就是create的一个axios 实例)异步加载(使用.then)
  • 可以看看没经过request.js封装的axios本体:
axios.get('/student',{
  params:{
    name:"邹xx"
  }
})
.then(function(response){
  console.log(response);
})
.catch(function(error){
  console.log(error);
});
  • 这个function也就是保存respondata而已,跟this.list赋值response.data是一样的,从而我们根据url路径,method方法,通过封装的axios框架(输入参数,通过设置的proxy代理组合路由,等等),发送请求,得到了后端传来的response.data

axios源码浅析,网络编程:到底是如何发送http请求的?

Post前端数据

  • post可以允许多重参数

跨域配置

前端

  • vue.config.js
  • 配置位置在这里插入图片描述
  • 配置代码
   proxy: {
      [process.env.VUE_APP_BASE_API]: {
        target: 'http://localhost:8000/api/v1',
        ws: true,
        changeOrigin: true,
        pathRewrite: { ['^' + process.env.VUE_APP_BASE_API]: '' }
      }
    }

后端

  • 如何全局搜素(快捷键被占用问题)
  • 右键在这里插入图片描述
  • 找到cors.go一般在Middleware中间件里
  • (不保证有效)
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin") //请求头部
		if origin != "" {
			//接收客户端发送的origin (重要!)
			c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
			//服务器支持的所有跨域请求的方法
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
			//允许跨域设置可以返回其他子段,可以自定义字段
			c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session")
			// 允许浏览器(客户端)可以解析的头部 (重要)
			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers")
			//设置缓存时间
			c.Header("Access-Control-Max-Age", "172800")
			//允许客户端传递校验信息比如 cookie (重要)
			c.Header("Access-Control-Allow-Credentials", "true")
		}

		//允许类型校验
		if method == "OPTIONS" {
			c.JSON(http.StatusOK, "ok!")
		}

		defer func() {
			if err := recover(); err != nil {
				log.Printf("Panic info is: %v", err)
			}
		}()

		c.Next()
	}

Error

低级错误

  • Syntax Error: Unexpected token (1:1292)

  • 符号错误:手滑打错!!!

  • 404 not found

  • 大概率手滑打错

如何获取token

  • 后端写好接口,一切正常的情况下
  • permission.js
  • 作用:在所有路由运行之前检查权限tokens
import router from './router'
import store from './store'

import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
import { getToken } from '@/utils/auth'

const whiteList = ['/login', '/auth-redirect', '/search/index']
NProgress.configure({ showSpinner: false }) // NProgress Configuration

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  const role = 'admin'
  const accessRoutes = await store.dispatch('permission/generateRoutes', role)
  next()
  router.addRoutes(accessRoutes)
  if (getToken()) {
    store.dispatch('user/getInfo')
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      next('/login')
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

Vuex store

加载loading问题

加载符号圈圈Loading

  • 在大的table容器中,有这样一句声明
v-loading="listLoading"
  • 默认true,就是默认正在加载数据而不是加载完成
  • 需要在data的return中加上listLoading: true,
  • 最后,在你的函数中得到response.data.data后记得让他设为false
  • this.listLoading=false
  • 否则无法显示数据,只显示加载符号(转圈圈)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值