美文网首页
vue-element-template4.0 实现上传文件

vue-element-template4.0 实现上传文件

作者: 莫道_bf96 | 来源:发表于2020-01-14 18:52 被阅读0次

本例是实现一个文件上传界面。

1. 修改路由,使用静态路由

# src/route/index.js 中修改
  {
    path: '/tools',
    component: Layout,
    redirect: '/tools/upload',
    name: 'Tools',
    meta: { title: 'Tool', icon: 'dashboard' },
    children: [
      {
        path: 'upload',
        name: 'upload',
        component: () => import('@/views/upload/index'),
        meta: { title: '上传文件', icon: 'dashboard' }
      }
]
}

2.增加vue文件

# src/views/upload 目录下,新建index.vue 
# 复制 [https://element.eleme.cn/#/zh-CN/component/upload](https://element.eleme.cn/#/zh-CN/component/upload)的若干样例

#并进行js 修改,如提交链接等

如何调试?

因为之前开启了mock进行数据访问,所以,如何保证请求如何正确的路由到后端接口进行联调就变成了一个问题。
幸运的是vue-template 集成了这种能力,可以使用proxy插件就能改变路由,非常方便。

# 修改 vue.config.js
 devServer: {
    port: port,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    proxy: {
      // change xxx-api/login => mock/login
      // detail: https://cli.vuejs.org/config/#devserver-proxy
      [process.env.VUE_APP_BASE_API]: {
//        target: `http://127.0.0.1:${port}/mock`,
        target: `http://127.0.0.1:8080`,
        changeOrigin: true,
        pathRewrite: {
          ['^' + process.env.VUE_APP_BASE_API]: ''
        }
      }
    }

Q2. 调试报错,无法成功返回。

定位问题是返回结构无法正确处理。
进一步定位发现是框架进行了统一的拦截处理。

#src/utils/request.js ,解决方案,注释这个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 !== 20000) {
      Message({
        message: res.message || '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()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
    
    
  },

相关文章

网友评论

      本文标题:vue-element-template4.0 实现上传文件

      本文链接:https://www.haomeiwen.com/subject/xpioactx.html