vue2+若依框架plus交互 路由介绍

本周及寒假

参加了校企合作的工程过程管理,和学长学姐一起写项目,之前学了vue也没有应用,然后对框架很多组件的用法不太了解,前期耽误了一些时间。

框架模块

首先是框架模块的介绍 api 存了一些系统管理及发送请求的方法

例如project.js

javascript 复制代码
import request from '@/utils/request'
import { getToken } from '@/utils/auth'
//添加新的公司
let token = getToken();
export function getTypeOnline(compName, compType) {
    return request({
        url: `/project/queryCompany?name=${compName}&type=${compType}`,
        headers: {
            isToken: true,
            token: `Bearer ${token}`
        },
        method: 'post',
     
    })
}

然后是asset 文件夹 存了文件的静态资源

component存的是用到的组件 layout也是组件 可以将页面的组件拆分展示成多个

plugins仿制的是插件进行鉴权等等,router是路由配置文件 store放置的是拆分出来的vuex里面的分模块化的内容

路由配置

菜单配置路由

若依框架可以通过菜单进行路由配置 进入系统管理的菜单管理

通过改变菜单的目录和菜单进行配置 输入组件路径和路由地址 既可以在左边侧边栏渲染出导航栏

路由配置

这是我配置的路由 因为本来在菜单设置的三级路由一直报错 这个配置的路由可以通过

meta: { title: '首页'}渲染你面包屑

javascript 复制代码
 {
    path: '',
    component: Layout,
    redirect: 'homePage',
    meta: { title: '首页', icon: 'dashboard', affix: true },
    children: [
      {
        path: 'homePage',
        component: () => import('@/views/home/homePage'),
        name: 'homePage',
        meta: { title: '公司库', icon: 'dashboard', affix: true },
        children:[
        ]
      },
        {
            path: 'project',
            component: () => import('@/views/home/projectManeger'),
            name: 'Project',
            meta: { title: '工程管理', icon: 'dashboard', affix: true },
            children: [{
              path: 'projectMain/:param',
              props: true,
              component: () => import('@/views/home/projectMain'),
              name: 'projectMain',
              hidden: true,
              meta: { title: '工程详情', icon: 'dashboard', affix: true, }
            }
            ],
          },
    ]
  },

登录逻辑

若依的登录逻辑是写好了的 在login.vue我们可以看到如下代码

javascript 复制代码
 handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove('rememberMe');
          }
         this.$store.dispatch("Login", this.loginForm)
          .then(() => {
            this.$router.push({ path: '/home/homePage' || "/" }).catch(()=>{});
          }).catch(() => {
            this.loading = false;
            if (this.captchaEnabled) {
              this.getCode();
            }
          });
        }
      });
    }

可以看出登录调用的是vuex里面的内容 可以在store->modules->user.js里面控制

在action可以看到

javascript 复制代码
Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid).then(res => {
          setToken(res.data.token)
          commit('SET_TOKEN', res.data.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

发送请求的login方法在src/api/login.js中

这个request是若依封装的拦截器

javascript 复制代码
import request from '@/utils/request'

// 登录方法
export function login(username, password, code, uuid) {
  const data = {
    username,
    password,
    code,
    uuid
  }
  return request({
    url: '/login',
    headers: {
      isToken: false
    },
    method: 'post',
    data: data
  })
}

存储token的部分 在src/utils/auth.js中

javascript 复制代码
import Cookies from 'js-cookie'

const TokenKey = 'Admin-Token'

export function getToken() {
  return Cookies.get(TokenKey)
}

export function setToken(token) {
  return Cookies.set(TokenKey, token)
}

export function removeToken() {
  return Cookies.remove(TokenKey)
}

交互

写的是分页 点击删除之后更新 所以把数据以及页数存储到了vuex中

html 复制代码
<template>
  <div class="componnentMain">
    <div class="addNewCom">
      <button @click="addNewomponent('add-newCoponent')" id="addnewBtn">
        新增
      </button>
      <el-dialog :title="dialogComtitle" :visible.sync="addDialogCom">
        <template v-if="currentComponent == 'add-newCoponent'">
          <add-newCoponent :addDialogCom.sync="addDialogCom" />
        </template>
        <template v-else>
          <edit-comVue
            :addDialogCom.sync="addDialogCom"
            :listData="ownlistData"
          />
        </template>
      </el-dialog>
    </div>
    <el-table :data="dataList" style="width: 97%" class="comLable">
      <el-table-column prop="compName" label="公司名称" width="260">
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="195">
        <template slot-scope="{ row }">
          {{ turnshowTime(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="compType" label="公司类别" width="190">
      </el-table-column>
      <el-table-column prop="compInvite" label="注册邀请码" width="330">
        <template slot-scope="{ row }">
          <span class="address-container">{{ row.compInvite }}</span>
          <!-- img 放在 span 之后 -->
          <img
            class="copyVisit"
            src="@/assets/images/copy.png"
            alt=""
            srcset=""
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="241" fixed="right">
        <template slot-scope="{ row }">
          <span class="combtn" @click="editcomponent('edit - comVue', row)">
            详情
          </span>
          <span class="combtn" @click="editcomponent('edit - comVue', row)">
            编辑
          </span>
          <span class="deleteCom" @click="delteCompany(row.id)"> 删除 </span>
        </template>
      </el-table-column>
    </el-table>
    <div class="pageComChange">
      <div class="pageComChangeCenter">
        <el-pagination
          background
          layout="prev, pager,next"
          :page-count="Number(totalPages)"
          :current-page="currentPage"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>
javascript 复制代码
import { mapState, mapMutations, mapActions } from "vuex";
//先引入vuex模块
export default {
  components: {
    "add-newCoponent": addnewComVue,
    "edit-comVue": editComVue,
  },
  computed: {
    ...mapState("companyPage", [
      "pageSize",
      "totalPages",
      "dataList",
      "searchConten",
    ]),
  },
  currentPage: {
    get() {
      return this.currentPage;
    },
    set(val) {
      this.handleCurrentChange(val);
    },
  },
  mounted() {
    this.fetchData();
    //在挂载调用一次分页接口
  },

  methods: {
    addNewomponent(componentType) {
      this.currentComponent = componentType;
      this.addDialogCom = !this.addDialogCom;
      this.dialogComtitle = "新建公司";
    },
    editcomponent(componentType, rowData) {
      this.currentComponent = componentType;
      this.addDialogCom = !this.addDialogCom;
      this.dialogComtitle = "修改公司信息";
      this.ownlistData = rowData;
    },
    ...mapMutations("companyPage", [
      "searchCompanysendMethos",
      "updatePagination",
    ]),
    ...mapActions("companyPage", ["serachComoanyactions", "fetchData"]),

    handleCurrentChange(val) {
      this.currentPage = val;
      if (this.searchConten == "" || this.searchType == "") {
        this.updatePagination({
          currentPage: val,
          pageSize: this.pageSize,
        });
        this.fetchData();
      } else {
        this.searchCompanysendMethos({
          currentPage: 1,
          pageSize: this.pageSize,
          searchConten: this.searchComvalue,
          searchType: this.searchType,
        });
        this.serachComoanyactions();
      }
    },
    delteCompany(id) {
      this.$confirm("确定要删除该公司吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const comids = [id];
          deleteCompany(comids).then((data) => {
            if (data.code == 200) {
              this.$message.success('删除公司成功')
              //这是判断有没有搜索内容
              if (this.searchConten == "" || this.searchType == "") {
                this.updatePagination({
                  currentPage:this.currentPage,
                  pageSize: this.pageSize,
                });
                this.fetchData();
              } else {
                this.searchCompanysendMethos({
                  currentPage: 1,
                  pageSize: this.pageSize,
                  searchConten: this.searchComvalue,
                  searchType: this.searchType,
                });
                this.serachComoanyactions();
              }
            } else {
              this.$message.error("删除该公司失败");
            }
          });
        })
        .catch((error) => {
          console.log(error);
        });
    },
    turnshowTime(timestamp) {
      // 使用导入的时间转换方法
      return turnshowTime(timestamp);
    },
  },
  data() {
    return {
      currentComponent: "",
      dialogComtitle: "",
      addDialogCom: false,
      currentPage: 1,
      ownlistData: {},
    };
  },
};

首先先注册模块

javascript 复制代码
//store/index.vue
const store = new Vuex.Store({
  modules: {
    app,
    dict,
    user,
    tagsView,
    permission,
    settings,
    companyPage,
    projectPage
  },
  getters
})

模块里面的命名空间要设置为true 并进行传递数据的更新

javascript 复制代码
import { getAllCompany,getSearchCompany} from "../../api/company";
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const companyPage=({
  namespaced: true,
  state: {
  currentPage: 1,
  pageSize: 10,
  totalPages: 0,
  searchConten:'',
  searchType:"",
  dataList: [] // 存储数据列表
  },
  mutations: {
  updatePagination(state, payload) {
    state.currentPage = payload.currentPage;
    state.pageSize = payload.pageSize;
    state.totalPages = payload.totalPages;
    
  },
  updateDataList(state, dataList) {
    state.dataList = dataList;
  },
  searchCompanysendMethos(state, payload) {
    state.currentPage = payload.currentPage;
    state.pageSize = payload.pageSize;
    state.totalPages = payload.totalPages;
    state.searchType=payload.searchType,
    state.searchConten=payload.searchConten
  },
  updateSearchList(state, dataList) {
    state.dataList = dataList;
  }
  },
 actions: {
  async fetchData({ commit, state }) {
    try {
    // 调用接口获取公司数据
    const response = await getAllCompany(state.pageSize,state.currentPage);
    // 更新分页状态
    commit('updatePagination', {
      currentPage: state.currentPage,
      pageSize: state.pageSize,
      totalPages: response.pages,
      dataList:response.records,

    });

    // 更新数据列表
    commit('updateDataList', response.records);
    } catch (error) {
    console.error('Error fetching company data:', error);
    }
  },
  async serachComoanyactions ({ commit, state }) {
    try {
    // 调用接口获取公司数据
    const response = await getSearchCompany(state.pageSize,state.currentPage,state.searchConten,state.searchType);
    commit('searchCompanysendMethos', {
      currentPage: state.currentPage,
      pageSize: state.pageSize,
      totalPages: response.pages,
      dataList:response.records,

    });

    // 更新数据列表
    commit('updateDataList', response.records);
    } catch (error) {
    console.error('Error fetching company data:', error);
    }
  }
}
});
export default companyPage

总结

vue写项目比之前用原生js写项目代码量要少得多 同时 框架好用是好用 但是要了解他的项目架构以及自带的一些方法

下周计划

先完成项目 然后学习一下ts 寒假没完全学完

相关推荐
m0_748247552 小时前
Web 应用项目开发全流程解析与实战经验分享
开发语言·前端·php
m0_748255022 小时前
前端常用算法集合
前端·算法
真的很上进3 小时前
如何借助 Babel+TS+ESLint 构建现代 JS 工程环境?
java·前端·javascript·css·react.js·vue·html
web130933203983 小时前
vue elementUI form组件动态添加el-form-item并且动态添加rules必填项校验方法
前端·vue.js·elementui
NiNg_1_2343 小时前
Echarts连接数据库,实时绘制图表详解
前端·数据库·echarts
如若1234 小时前
对文件内的文件名生成目录,方便查阅
java·前端·python
滚雪球~4 小时前
npm error code ETIMEDOUT
前端·npm·node.js
沙漏无语4 小时前
npm : 无法加载文件 D:\Nodejs\node_global\npm.ps1,因为在此系统上禁止运行脚本
前端·npm·node.js
supermapsupport4 小时前
iClient3D for Cesium在Vue中快速实现场景卷帘
前端·vue.js·3d·cesium·supermap
brrdg_sefg4 小时前
WEB 漏洞 - 文件包含漏洞深度解析
前端·网络·安全