vue+elementui项目总结

1.为了避免一层一层的找文件路径带来的错误,可以通过设置别名的方式来解决,在vue.config.js(vuecli新版本的构建项目,需要自己创建)里设置(设置成功后一定要重启项目)

const path = require('path'); //引入path模块
function resolve(dir) {
  return path.join(__dirname, dir) //path.join(__dirname)设置绝对路径
}
module.exports = {
   //配置别名
  //set第一个参数:设置的别名,第二个参数:设置的路径
  chainWebpack: (config) => {
    config.resolve.alias
      .set('@', resolve('src'))
      .set('components', resolve('src/components'))
      .set('assets', resolve('src/assets'))
      .set('views', resolve('src/views'))

  }
}

在index.js中引用

const routes = [{
    path: '/',
    redirect: '/Login'
  },
  {
    path: '/Login',
    component: () => import('views/Login.vue')
  },
  {
    path: '/Home',
    component: () => import('components/Home.vue'),
    redirect:'/Enterprise'
 }
]

注意:引用图片资源时,记的在template和style里加~(否则报错) ,js里不需要加

background: url(~assets/image/login_bg.png) no-repeat;
import 'assets/css/global.css'

2.为了方便项目的维护,将所有的接口都封装到一个文件中,在view下新建个api文件夹,包含http.js(封装请求)api.js(封装各个接口),同时涉及本地存储将登录获取的token,带在请求头上(vuex)

http.js

import axios from 'axios'
axios.defaults.baseURL ='/';

const http = axios.create({
	timeout: 300 * 1000,
	headers: {
		'Cache-Control': 'no-cache'
	}
});
//http request 拦截器
http.interceptors.request.use(config => {
      //接口带token请求头
       if (localStorage.getItem('Authorization')) {
          config.headers.token = localStorage.getItem('Authorization');
        }
        return config;
    },
    error => {
        return Promise.error(error);
    })

 //http response 拦截器
 http.interceptors.response.use(response => {
        if (response.status === 200) {
            return Promise.resolve(response);
        } else {
            return Promise.reject(response);
        }
  }, error => {
      return Promise.reject(error);
  })
  export default  http

api.js

import http from './http.js'
// 登录
export const login = data => {
  return http.post('backend/user/login',data);
}
//查找父行业,不传参数
export const  BESVocation = () => {
   return http.get('backend/enterprls/queryBESVocation');
}
//根据父行业查找子行业
export const ByChiid = data=>{
  return http.get('backend/vocation/queryByChiid',data)
}

//信息管理页表格数据
export const EnterpriseTable = data =>{
  return http.get('backend/enterprls/getEnterprlsList',data)
}
//停用数据 1  企业管理
export const EnterprlsState = data=>{
	return http.get('backend/enterprls/activatingEnterprlsState',data)
}
//加入活动接口 
export const batchAdd = data =>{
	return http.post('backend/enterprls/batchAdd',data)
}

现在以登录接口为例,在login.vue中先引用

import {login} from '../api/api.js'

接下来调接口

 loginFrom() {
        //验证通过了异步请求数据
        this.$refs.loginFromRefs.validate( async valid => {
          if (!valid) return;
          if (valid) {
            const {
              data: res
            } = await login(this.$qs.stringify(this.loginForm))
            console.log(res);
            if (res.code == 1002) {
              return this.$Message.error('该用户不存在,请使用正确账号登录');
            }else if(res.code == 1001){
                this.$Message.error("请输入正确密码");
                this.loginForm.tuPwd = '';
                return;
            }else if(res.code == 200){
              // window.sessionStorage.setItem('token', 'zhlz');
               this.$Message.success('登录成功');
               this.$router.push('/Home');
              //将token和username传到vuex中
              this.changeLogin({ Authorization: res.data.token });
              this.$store.commit('handleUserName',res.data.username);
            }
          }
        })
      },

如图

vue+elementui项目总结_第1张图片

vue+elementui项目总结_第2张图片

需要vuex,在store文件下index中(项目构建的时候自动生成)

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 存储token
    //防止页面刷新,导致vuex重新启动,用户名和token成为初始值(初始值为空)的情况
    Authorization: localStorage.getItem('Authorization') ? localStorage.getItem('Authorization') : '',
    username: localStorage.getItem('username') ? localStorage.getItem('username') : '',
  },
  mutations: {
    // 修改token,并将token存入localStorage
    changeLogin(state, user) {
      state.Authorization = user.Authorization;
      localStorage.setItem('Authorization', user.Authorization);
    },
    //用户登录
    handleUserName(state,user){
      state.username = user;
      localStorage.setItem('username', user);
    }
  },
   getters:{
    userName: (state) => state.username
  },
  modules: {}
})

在页面中引用,即可

{{$store.getters.userName}}

 

3.由于elementui组件库非常大,我们只需要引用自己需要用到的组件即可,按需引用

以引用Button组件为例,然后在main.js(入口文件)中引入即可

import Vue from 'vue'
import 'element-ui/lib/theme-chalk/index.css'
import { Button} from 'element-ui'
Vue.use(Button)

4.由于页面中多次会用到提示组件和confirm组件,同样先按需引用,注册成全局的

import { Message,  MessageBox} from 'element-ui'
Vue.prototype.$Message = Message
Vue.prototype.$confirm = MessageBox.confirm

例如成功组件就可以简写成

this.$Message.success('登录成功');

confirm组件在用户进行操作的时候提示,由于是异步的操作,根据用户操作返回的是confirm还是cancle来进行对应操作

    //停用数据
      async stopUseData(enterprlsId) {
        this.EnterprlsStop.enterprlsId = enterprlsId;
        const confirmResult = await this.$confirm('将停用该数据, 是否确定?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)

        if (confirmResult !== 'confirm') {
          return this.$Message.info('已取消停用该数据');
        }
        let {
          data: res
        } = await EnterprlsState({
          params: this.EnterprlsStop
        });
        if (res.code != 200) {
          return this.$Message.error('停用该数据失败');
        }
        this.$Message.success('停用数据成功');
        this.getTableData();
      },

5.在使用table表格中使用select方法,接受两个参数,selection,与row,通过查看selection是否包含row来判断是勾选了复选框还是取消了(true-勾选,0-取消)

 //勾选企业
      selectCheck(selection, row) {
        let selected = selection.length && selection.indexOf(row) !== -1;
        //勾选
        if (selected) {
          this.EnterprlActivity.numbers.push(row.enterprlsId);
        } else {
          //取消勾选
          this.EnterprlActivity.numbers = this.EnterprlActivity.numbers.filter(item => item != row.enterprlsId);
        }
      },

如图:

 

 

vue+elementui项目总结_第3张图片

6.导出excle表格,先新建一个文件夹vendor,新建Blob.js和Export2Excel.js

Blob.js

(function (view) {
  "use strict";

  view.URL = view.URL || view.webkitURL;

  if (view.Blob && view.URL) {
      try {
          new Blob;
          return;
      } catch (e) {}
  }

  // Internally we use a BlobBuilder implementation to base Blob off of
  // in order to support older browsers that only have BlobBuilder
  var BlobBuilder = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder || (function(view) {
          var
              get_class = function(object) {
                  return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
              }
              , FakeBlobBuilder = function BlobBuilder() {
                  this.data = [];
              }
              , FakeBlob = function Blob(data, type, encoding) {
                  this.data = data;
                  this.size = data.length;
                  this.type = type;
                  this.encoding = encoding;
              }
              , FBB_proto = FakeBlobBuilder.prototype
              , FB_proto = FakeBlob.prototype
              , FileReaderSync = view.FileReaderSync
              , FileException = function(type) {
                  this.code = this[this.name = type];
              }
              , file_ex_codes = (
                  "NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR "
                  + "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR"
              ).split(" ")
              , file_ex_code = file_ex_codes.length
              , real_URL = view.URL || view.webkitURL || view
              , real_create_object_URL = real_URL.createObjectURL
              , real_revoke_object_URL = real_URL.revokeObjectURL
              , URL = real_URL
              , btoa = view.btoa
              , atob = view.atob

              , ArrayBuffer = view.ArrayBuffer
              , Uint8Array = view.Uint8Array
              ;
          FakeBlob.fake = FB_proto.fake = true;
          while (file_ex_code--) {
              FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;
          }
          if (!real_URL.createObjectURL) {
              URL = view.URL = {};
          }
          URL.createObjectURL = function(blob) {
              var
                  type = blob.type
                  , data_URI_header
                  ;
              if (type === null) {
                  type = "application/octet-stream";
              }
              if (blob instanceof FakeBlob) {
                  data_URI_header = "data:" + type;
                  if (blob.encoding === "base64") {
                      return data_URI_header + ";base64," + blob.data;
                  } else if (blob.encoding === "URI") {
                      return data_URI_header + "," + decodeURIComponent(blob.data);
                  } if (btoa) {
                      return data_URI_header + ";base64," + btoa(blob.data);
                  } else {
                      return data_URI_header + "," + encodeURIComponent(blob.data);
                  }
              } else if (real_create_object_URL) {
                  return real_create_object_URL.call(real_URL, blob);
              }
          };
          URL.revokeObjectURL = function(object_URL) {
              if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) {
                  real_revoke_object_URL.call(real_URL, object_URL);
              }
          };
          FBB_proto.append = function(data/*, endings*/) {
              var bb = this.data;
              // decode data to a binary string
              if (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) {
                  var
                      str = ""
                      , buf = new Uint8Array(data)
                      , i = 0
                      , buf_len = buf.length
                      ;
                  for (; i < buf_len; i++) {
                      str += String.fromCharCode(buf[i]);
                  }
                  bb.push(str);
              } else if (get_class(data) === "Blob" || get_class(data) === "File") {
                  if (FileReaderSync) {
                      var fr = new FileReaderSync;
                      bb.push(fr.readAsBinaryString(data));
                  } else {
                      // async FileReader won't work as BlobBuilder is sync
                      throw new FileException("NOT_READABLE_ERR");
                  }
              } else if (data instanceof FakeBlob) {
                  if (data.encoding === "base64" && atob) {
                      bb.push(atob(data.data));
                  } else if (data.encoding === "URI") {
                      bb.push(decodeURIComponent(data.data));
                  } else if (data.encoding === "raw") {
                      bb.push(data.data);
                  }
              } else {
                  if (typeof data !== "string") {
                      data += ""; // convert unsupported types to strings
                  }
                  // decode UTF-16 to binary string
                  bb.push(unescape(encodeURIComponent(data)));
              }
          };
          FBB_proto.getBlob = function(type) {
              if (!arguments.length) {
                  type = null;
              }
              return new FakeBlob(this.data.join(""), type, "raw");
          };
          FBB_proto.toString = function() {
              return "[object BlobBuilder]";
          };
          FB_proto.slice = function(start, end, type) {
              var args = arguments.length;
              if (args < 3) {
                  type = null;
              }
              return new FakeBlob(
                  this.data.slice(start, args > 1 ? end : this.data.length)
                  , type
                  , this.encoding
              );
          };
          FB_proto.toString = function() {
              return "[object Blob]";
          };
          FB_proto.close = function() {
              this.size = this.data.length = 0;
          };
          return FakeBlobBuilder;
      }(view));

  view.Blob = function Blob(blobParts, options) {
      var type = options ? (options.type || "") : "";
      var builder = new BlobBuilder();
      if (blobParts) {
          for (var i = 0, len = blobParts.length; i < len; i++) {
              builder.append(blobParts[i]);
          }
      }
      return builder.getBlob(type);
  };
}(typeof self !== "undefined" && self || typeof window !== "undefined" && window || this.content || this));

Export2Excel.js

/* eslint-disable */

require('script-loader!file-saver');
import XLSX from 'xlsx'
// require('script-loader!@vendor/Blob');
// require('script-loader!xlsx/dist/xlsx.core.min');
function generateArray(table) {
    var out = [];
    var rows = table.querySelectorAll('tr');
    var ranges = [];
    for (var R = 0; R < rows.length; ++R) {
        var outRow = [];
        var row = rows[R];
        var columns = row.querySelectorAll('td');
        for (var C = 0; C < columns.length; ++C) {
            var cell = columns[C];
            var colspan = cell.getAttribute('colspan');
            var rowspan = cell.getAttribute('rowspan');
            var cellValue = cell.innerText;
            if (cellValue !== "" && cellValue == +cellValue) cellValue = +cellValue;

            //Skip ranges
            ranges.forEach(function (range) {
                if (R >= range.s.r && R <= range.e.r && outRow.length >= range.s.c && outRow.length <= range.e.c) {
                    for (var i = 0; i <= range.e.c - range.s.c; ++i) outRow.push(null);
                }
            });

            //Handle Row Span
            if (rowspan || colspan) {
                rowspan = rowspan || 1;
                colspan = colspan || 1;
                ranges.push({s: {r: R, c: outRow.length}, e: {r: R + rowspan - 1, c: outRow.length + colspan - 1}});
            }
            ;

            //Handle Value
            outRow.push(cellValue !== "" ? cellValue : null);

            //Handle Colspan
            if (colspan) for (var k = 0; k < colspan - 1; ++k) outRow.push(null);
        }
        out.push(outRow);
    }
    return [out, ranges];
};

function datenum(v, date1904) {
    if (date1904) v += 1462;
    var epoch = Date.parse(v);
    return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
}

function sheet_from_array_of_arrays(data, opts) {
    var ws = {};
    var range = {s: {c: 10000000, r: 10000000}, e: {c: 0, r: 0}};
    for (var R = 0; R != data.length; ++R) {
        for (var C = 0; C != data[R].length; ++C) {
            if (range.s.r > R) range.s.r = R;
            if (range.s.c > C) range.s.c = C;
            if (range.e.r < R) range.e.r = R;
            if (range.e.c < C) range.e.c = C;
            var cell = {v: data[R][C]};
            if (cell.v == null) continue;
            var cell_ref = XLSX.utils.encode_cell({c: C, r: R});

            if (typeof cell.v === 'number') cell.t = 'n';
            else if (typeof cell.v === 'boolean') cell.t = 'b';
            else if (cell.v instanceof Date) {
                cell.t = 'n';
                cell.z = XLSX.SSF._table[14];
                cell.v = datenum(cell.v);
            }
            else cell.t = 's';

            ws[cell_ref] = cell;
        }
    }
    if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
    return ws;
}

function Workbook() {
    if (!(this instanceof Workbook)) return new Workbook();
    this.SheetNames = [];
    this.Sheets = {};
}

function s2ab(s) {
    var buf = new ArrayBuffer(s.length);
    var view = new Uint8Array(buf);
    for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
    return buf;
}

export function export_table_to_excel(id) {
    var theTable = document.getElementById(id);
    console.log('a')
    var oo = generateArray(theTable);
    var ranges = oo[1];

    /* original data */
    var data = oo[0];
    var ws_name = "SheetJS";
    console.log(data);

    var wb = new Workbook(), ws = sheet_from_array_of_arrays(data);

    /* add ranges to worksheet */
    // ws['!cols'] = ['apple', 'banan'];
    ws['!merges'] = ranges;

    /* add worksheet to workbook */
    wb.SheetNames.push(ws_name);
    wb.Sheets[ws_name] = ws;

    var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: false, type: 'binary'});

    saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), "test.xlsx")
}

function formatJson(jsonData) {
    console.log(jsonData)
}
export function export_json_to_excel(th, jsonData, defaultTitle) {

    /* original data */

    var data = jsonData;
    data.unshift(th);
    var ws_name = "SheetJS";

    var wb = new Workbook(), ws = sheet_from_array_of_arrays(data);


    /* add worksheet to workbook */
    wb.SheetNames.push(ws_name);
    wb.Sheets[ws_name] = ws;

    var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: false, type: 'binary'});
    var title = defaultTitle || '列表'
    saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), title + ".xlsx")
}

在页面中引用

  //导出excel
     export2Excel() {
       import('@/vendor/Export2Excel').then(excel=>{
          const tHeader = [
             "企业名称",
             "联系人",
             "联系电话",
             "所在行业",
             "公司规模",
             "录入时间"
           ];
          const filterVal = [
             "enterprlsName",
             "contactsName",
             "contactsPhone",
             "vocation",
             "enterprlsScale",
             "foundDate"
           ];
           const list = this.newTableData;
           const data = this.formatJson(filterVal, list);
           if (list.length > 0) {
             excel.export_json_to_excel(tHeader, data, "企业管理数据列表");
             //清空勾选
             this.$refs.tableDataList.clearSelection();
           } else {
             return this.$Message.warning('请至少勾选一项,再进行操作');
           }
       })
     },

效果如图:

vue+elementui项目总结_第4张图片

7.对后台返回的时间戳进行日期转换(如果返回的是Invalid date,这时候要注意后台返回的是string,还是number)

vue+elementui项目总结_第5张图片

引用monent来进行日期格式转换,安装monent

npm install moment --save

在main.js 中全局引用

import Moment from 'moment'

// 定义全局时间戳过滤器
Vue.filter('formatDate', function(value) {
  return Moment(value).format('YYYY-MM-DD HH:mm:ss')
})

页面中引用

 
           
 

7.vue.config.js基础配置

const path = require('path'); //引入path模块
function resolve(dir) {
  return path.join(__dirname, dir) //path.join(__dirname)设置绝对路径
}
module.exports = {
  lintOnSave: false,//关闭eslint 校验代码
  publicPath: './',
  outputDir: 'dist',//打包输入目录
  assetsDir: 'static',//静态资源
  // 指定生成的 index.html 的输出路径 (相对于 outputDir)。也可以是一个绝对路径。
  indexPath: 'index.html',
  //配置别名
  //set第一个参数:设置的别名,第二个参数:设置的路径
  chainWebpack: (config) => {
    config.resolve.alias
      .set('@', resolve('src'))
      .set('components', resolve('src/components'))
      .set('assets', resolve('src/assets'))
      .set('views', resolve('src/views'))
      .set('uitls',resolve('src/uitls'))
  },
  //配置跨域
  devServer: {
    port: 8080,
    open: true, //自动打开
    overlay: {
      warnings: false,
      errors: true
    }, //报错就显示出来,警告就不显示
    proxy: {
      '/': {
        target: 'https://xxxx/',//域名
        changeOrigin: true, // 允许跨域
      }
    }
  },
}

8. 当用户打开是移动端的的时候跳转到一个链接,是pc又跳转到另一个

 
    //移动端
    if ((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
      window.location.href = "xxxx"
    }else{
      window.location.href = "xxxx"
    }

    console.log(navigator)

 

你可能感兴趣的:(vue)