当前位置: 代码迷 >> 综合 >> vue-cli4.x +elementUI项目记录2(登录+树形控件+分页)
  详细解决方案

vue-cli4.x +elementUI项目记录2(登录+树形控件+分页)

热度:6   发布时间:2024-02-21 18:44:30.0

登录的功能应该是放在第一篇的,昨天脑子不够用,今天这篇博客来补上,在登录的时候,在vuex对应的文件里面处理好数据
store------》index.js

import Vue from 'vue'
import Vuex from 'vuex'Vue.use(Vuex)export default new Vuex.Store({
    state: {
    userInfo: null,userData: null,refreshMark: null, searchTitle: null,},//利用getters对state存储的数据进行过滤getters: {
    getUserInfo(state) {
    return state.userInfo}, getUserName(state) {
    return state.userData},getRefresh(state){
    return state.refreshMark},getSearchTitle(state){
    return state.searchTitle}},// 利用mutations改变store的数据(同步的)mutations: {
    setSearchTitle(state, payload){
    state.searchTitle = payload},setUserInfo(state, payload) {
    state.userInfo = payload.userInfo},setUserName(state, payload){
    state.userData = payload},setRefresh(state, payload){
    state.refreshMark = payload}}
})

**

login.vue登录部分代码

**

<template><div class="login-container"><h1>CY</h1><h3>xxxxxxx管理系统</h3><!-- @keyup.enter.native:监听键盘回车事件 --><el-input class="input" type="text" placeholder="请输入用户名" @keyup.enter.native="onClickLogin" v-model="username" /><el-input class="input" type="password" show-password placeholder="请输入密码" @keyup.enter.native="onClickLogin" v-model="userpwd" /><el-button class="login-button" type="primary" @click="onClickLogin">登录</el-button></div>
</template><script>import Util from '../../Util/Util.js'import httpUtil from '../../Util/httpUtil.js'import qs from 'qs'import store from '../../store'export default {
    data () {
    return {
    username: '',userpwd: ''}},components: {
    },computed: {
    },mounted() {
    //如果有用户就登录let token = sessionStorage.getItem('userName');if (token == null || !token) {
    console.log("空");} else {
    this.$router.replace('/Home');}},methods: {
    onClickLogin(){
    let {
     username, userpwd } = this.$dataconsole.log(username)if(!username || !userpwd){
    this.$message.warning('用户名或密码不能为空')return false}//获取身份验证信息和设备idlet {
     authorization, deviceId } = Util.getAuthorizationInfo()// 通过commit方法提交到mutationthis.$store.commit('setRefresh', "1")//请求登录接口console.log(userpwd)this.httpRequest.httpPostRequest('/adminLogin/login',{
    username: username,password: userpwd,}).then((res) => {
    if(res.data.code == 20000){
    this.$message.success('登录成功')sessionStorage.setItem('userName', res.data.data.name);sessionStorage.setItem('userinfo', JSON.stringify(res.data.data.authorities[0]))this.$router.push({
     name:'Home' })console.log(this.$route.path)} else {
    this.$message.error(res.data.message)}}).catch((error) => {
    console.log(error)this.$message.error('网络错误,请稍后重试')})}}}</script>

封装的Util.js

import XLSX from 'xlsx'//xlsx是一个简单的JavaScript插件,读取和写入Excel表格//防抖函数时间ID
let antiShakeId = 0;
//设备ID
let deviceId = '';export default class Util {
    //检查有无签名static checkSecurity() {
    let tSignature = sessionStorage.getItem("signature");return tSignature;}//导出Exclestatic exportExcle(exportArray, filename = '默认') {
    let tSheet = XLSX.utils.aoa_to_sheet(exportArray);let wb = XLSX.utils.book_new();XLSX.utils.book_append_sheet(wb, tSheet, "SheetJS");XLSX.writeFile(wb, `${
     filename}.xls`);}//防抖函数static antiShake(callback, time) {
    if (antiShakeId) {
    clearTimeout(antiShakeId)}antiShakeId = setTimeout(callback, time);}//获取身份验证相关信息static getAuthorizationInfo() {
    //请求身份认证转换base64let tStr = "broadtree:CgG8tpmnHVfZD8jl";//生成随机设备idif (!deviceId) {
    deviceId = Util.getRandomCode();}return {
    authorization: btoa(tStr),deviceId: deviceId}}//随机字符串static getRandomCode() {
    let tString = ['A', 'B', 'C', 'D', 's', 'w', 'y', 'k', 'R', 'q', 'm'];let tCode = '';for (let i = 0; i < 10; i++) {
    tCode += tString[Util.wxRandom(0, 11)];}return tCode + Date.now();}//随机数取出static wxRandom(m, n) {
    var num = Math.floor(Math.random() * (m - n) + n);return num;}
}

树形控件核心代码部分(自定义节点内容的树形控件)


1、node-expand:节点展开的时候触发的事件
2、node-click:点击节点触发的事件

		<el-tree:data="companyList"node-key="id"props="defaultProps":default-expanded-keys="defaultKeys":accordion="true":highlight-current="true"@node-click="handleNodeClick":expand-on-click-node="true"><spanclass="custom-tree-node"style="display: flex; align-items: center"slot-scope="{ node,data }"><span style="font-size: 13px">{
    {
     data.name }}</span><span><el-buttonstyle="font-weight: bold;margin-left: 6px"type="text"size="mini"@click="() => append(node,data)">...</el-button></span></span></el-tree>

分页部分代码


分页在这里就很简单,传一些需要搜索的字段、当前页、每页显示多少条即可
1、@size-change:点击每页多少条时触发
2、@current-change:点击页数时触发

	<div class="pagination"><div></div><el-paginationclass="pnation"@size-change="handleSizeChange"@current-change="handleCurrentChange":current-page="currentPage":page-sizes="[5, 10, 20, 30]":page-size="pageSize"backgroundlayout="total, sizes, prev, pager, next, jumper":total="totalPage"></el-pagination></div>getEmployeeList这个方法也可以只传一个参数(Object),时间紧就按照简单的来了)// 选择每页多少条handleSizeChange(val) {
    console.log(`每页 ${
     val}`)this.pageSize = valthis.getEmployeeList(this.currentPage,this.pageSize)},// 跳转到第几页handleCurrentChange(val) {
    this.currentPage = valthis.getEmployeeList(this.currentPage,this.pageSize)},//获取数据列表getEmployeeList(currentPage,pageSize,mobile,gradeName,employeeName,companyName) {
    const loading = this.$loading({
    lock: true,text: '正在加载中',spinner: 'el-icon-loading',background: 'rgba(0, 0, 0, 0.7)'});this.httpRequest.httpGetRequest("employee/queryEmployee", {
    current: currentPage ? currentPage : 1,size: pageSize ? pageSize : 10,mobile: mobile ? mobile : '',gradeName: gradeName ? gradeName : '',employeeName: employeeName ? employeeName : '',companyName: companyName ? companyName : ''}).then((res) => {
    if (res.data.code == 20000) {
    setTimeout(() => {
    loading.close();}, 800);this.employeeList = res.data.data.recordsthis.totalPage = res.data.data.total}if (res.data.code == 20001) {
    this.$message.error("获取数据失败")}}).catch((error) => {
    this.$message.error("获取数据失败")});},
  相关解决方案