VUE增删改查页面实例

main.js

import Vue from 'vue'
import App from './App.vue'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import './assets/Global.css'
import axios from "axios";
import VueRouter from 'vue-router';
import router from "./router";
import store from "./store";

Vue.prototype.$axios =axios;
Vue.prototype.$httpUrl="http://localhost:8081";
Vue.config.productionTip = false

Vue.use(VueRouter);
Vue.use(ElementUI,{size:'small'});
new Vue({
  router,
  store,
  render: h => h(App),
}).$mount('#app')

App.vue

<template>
  <div id="app">
    <router-view/>
  div>
template>

<script>

export default {
  name: 'App',
  components: {

  }
}
script>

<style>
#app {
  height: 100%;
}
style>

/router/index.js

import VueRouter from 'vue-router';

const routes = [
    {
        path:'/',
        name:'login',
        component:()=>import('../components/Login')
    },
    {
        path:'/Index',
        name:'index',
        component:()=>import('../components/IndexVue'),
        children:[
            {
                path:'/Home',
                name:'home',
                media:{
                  title:'首页'
                },
                component:()=>import('../components/Home')
            }
        ]
    }
]

const router = new VueRouter({
    mode:'history',
    routes
})
export default router;
export function resetRouter() {
    router.matcher = new VueRouter({
        mode:'history',
        routes: []
    }).matcher
}

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

/store/index.js

import vue from 'vue'
import Vuex from 'vuex'
import router,{resetRouter} from "@/router";
vue.use(Vuex)
function addNewRoute(menuList) {
    console.log(menuList)
    let routes = router.options.routes
    console.log(routes)
    routes.forEach(routeItem=>{
        if(routeItem.path=="/Index"){
            menuList.forEach(menu=>{
                let childRoute =  {
                    path:'/'+menu.menuclick,
                    name:menu.menuname,
                    meta:{
                        title:menu.menuname
                    },
                    component:()=>import('../components/'+menu.menucomponent)
                }

                routeItem.children.push(childRoute)
            })
        }
    })

    resetRouter()
    router.addRoutes(routes)
}
export default new Vuex.Store({
    state: {
        menu: []
    },
    mutations: {
        setMenu(state,menuList) {
            state.menu = menuList

            addNewRoute(menuList)
        }
    },
    getters: {
        getMenu(state) {
            return state.menu
        }
    }
})

indexVue.vue

<template>
  <el-container style="height: 100%; border: 1px solid #eee">
    <el-aside :width="aside_width" style="background-color: rgb(238, 241, 246);height: 100%;margin-left: -1px">
      <Aside :isCollapse="isCollapse">Aside>
    el-aside>

    <el-container style="height: 100%; ">
      <el-header style="text-align: right; font-size: 12px;height: 100%;border-bottom: rgba(169,169,169,0.3) 1px solid">
        <Header @doCollapse="doCollapse" :icon="icon">Header>
      el-header>

      <el-main style="height: 100%;">
        <router-view/>
      el-main>
    el-container>
  el-container>
template>

<script>



import Aside from "@/components/Aside";
import Header from "@/components/Header";

export default {
  name: "IndexVue",
  components:{
    Aside,
    Header
  },
  data(){
    return{
      isCollapse:false,
      aside_width:'200px ',
      icon:'el-icon-s-fold'

    }
  },
  methods:{
    doCollapse(){
      //console.log(11111);
      this.isCollapse = !this.isCollapse
      if(!this.isCollapse){
        this.aside_width='200px'
        this.icon='el-icon-s-fold'
      }else {
        this.aside_width='64px'
        this.icon='el-icon-s-unfold'

      }
    }
  }

}
script>

<style scoped>
.el-header {
  #background-color: #B3C0D1;
  color: #333;
  line-height: 60px;
}

.el-aside {
  color: #333;
}
.el-main {
  padding: 5px;
}
style>

Aside.vue

<template>
  <el-menu
      background-color="#545c64"
      text-color="#fff"
      active-text-color="#ffd04b"
      default-active="Home"
      :collapse="isCollapse"
      :collapse-transition="false"
      style="height: 100vh"
      router>
    <el-menu-item index="/Home">
      <i class="el-icon-s-home">i>
      <span slot="title">首页span>
    el-menu-item>
    <el-menu-item :index="'/'+item.menuclick"  v-for="(item,i) in menu" :key="i">
      <i :class="item.menuicon">i>
      <span slot="title">{{item.menuname}}span>
    el-menu-item>

  el-menu>

template>

<script>
export default {
  name: "Aside",
  data(){
    return{
      //isCollapse : true
      // menu:[
      //   {
      //     menuClick:'Admin',
      //     menuName:'管理员',
      //     menuIcon:'el-icon-s-custom'
      //   },{
      //     menuClick:'User',
      //     menuName:'用户',
      //     menuIcon:'el-icon-user-solid'
      //   }
      // ]
    }
  },
  computed:{
    "menu":{
      get(){
        return this.$store.state.menu
      }
    }
  },
  props:{
    isCollapse:Boolean
  }
}
script>

<style scoped>

style>

Header.vue

<template>
  <div style="display: flex;line-height: 60px">
    <div style="margin-top: 8px ">
      <i :class="icon" style="font-size: 20px;cursor: pointer" @click="collapse">i>
    div>
    <div style="flex: 1;text-align: center;font-size: 34px">
      <span>欢迎来到仓库管理系统span>
    div>
    <el-dropdown>
      <span>{{user.name}}<i class="el-icon-arrow-down" style="margin-left: 5px;">i>span>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item @click.native="toUser">个人中心el-dropdown-item>
        <el-dropdown-item @click.native="logOut">退出登陆el-dropdown-item>
      el-dropdown-menu>
    el-dropdown>
  div>
template>

<script>
export default {
  name: "header",
  data(){
    return{
      user : JSON.parse(sessionStorage.getItem('CurUser'))
    }
  },
  props:{
    icon:String
  },
  methods:{
    toUser(){
      console.log("toUser")
      this.$router.push("/Home")

    },
    logOut(){

      this.$confirm('确定?','提示',{
        confirmButtonText:'确定',
        type:'warning',
        center:true
      })

      .then(()=>{
         this.$message({
           type:"success",
           message:'退出登录成功'
         })
        console.log("logout")
        this.$router.push("/")
      })

      .catch(() => {
        this.$message({
          type:"info",
          message:'取消'
        })
      })


    },
    collapse(){
      this.$emit('doCollapse')
      sessionStorage.clear()
    }

  },
  created(){
    this.$router.push("/Home")
  }

}
script>

<style scoped>

style>

Home.vue

<template>
    <div style="text-align: center;background-color: #f1f1f3;height: 100%;padding: 0px;margin: 0px;">
        <h1 style="font-size: 50px;">{{'欢迎你!'+user.name}}h1>
        <el-descriptions  title="个人中心" :column="2" size="40" border>
            <el-descriptions-item>
                <template slot="label">
                    <i class="el-icon-s-custom">i>
                    账号
                template>
                {{user.no}}
            el-descriptions-item>
            <el-descriptions-item>
                <template slot="label">
                    <i class="el-icon-mobile-phone">i>
                    电话
                template>
                {{user.phone}}
            el-descriptions-item>
            <el-descriptions-item>
                <template slot="label">
                    <i class="el-icon-location-outline">i>
                    性别
                template>
                <el-tag
                        :type="user.sex === '1' ? 'primary' : 'danger'"
                        disable-transitions><i :class="user.sex==1?'el-icon-male':'el-icon-female'">i>{{user.sex==1?"男":"女"}}el-tag>
            el-descriptions-item>
            <el-descriptions-item>
                <template slot="label">
                    <i class="el-icon-tickets">i>
                    角色
                template>
                <el-tag
                        type="success"
                        disable-transitions>{{user.roleId==0?"超级管理员":(user.roleId==1?"管理员":"用户")}}el-tag>

            el-descriptions-item>
        el-descriptions>

        <DateUtils>DateUtils>
    div>
template>

<script>
    import DateUtils from "./DateUtils";
    export default {
        name: "Home",
        components: {DateUtils},
        data() {

            return {
                user:{}
            }
        },
        computed:{

        },
        methods:{
            init(){
                this.user = JSON.parse(sessionStorage.getItem('CurUser'))
            }
        },
        created(){
            this.init()
        }
    }
script>

<style scoped>
    .el-descriptions{
        width:90%;

        margin: 0 auto;
        text-align: center;
    }
style>

/user/UserManager.vue

<template>
  <div>
    <div style="margin-bottom: 5px">
      <el-input v-model="name" placeholder="请输入名字:" suffix-icon="el-icon-search" style="width:200px;"
                @keyup.enter.native="loadPost">el-input>
      <el-select v-model="sex" filterable placeholder="请选择性别" style="margin-left: 5px">
        <el-option
            v-for="item in sexs"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        el-option>
      el-select>
      <el-button type="primary"  style="margin-left: 5px" @click="loadPost">查询el-button>
      <el-button type="success" @click="resetParam">重置el-button>
      <el-button type="primary"  style="margin-left: 5px" @click="add">新增el-button>


    div>
    <el-table :data="tableData"
              :header-cell-style="{background:'dark'}"
              border
    >
      <el-table-column prop="id" label="ID" width="60">
      el-table-column>
      <el-table-column prop="no" label="账号" width="120">
      el-table-column>
      <el-table-column prop="name" label="姓名" width="120">
      el-table-column>
      <el-table-column prop="password" label="密码" width="120">
      el-table-column>
      <el-table-column prop="age" label="年龄" width="60">
      el-table-column>
      <el-table-column prop="sex" label="性别" width="120">
        <template slot-scope="scope">
          <el-tag
              :type="scope.row.sex === 1 ? 'primary' : 'success'"
              disable-transitions>{{scope.row.sex === 1 ? '男' : '女'}}el-tag>
        template>
      el-table-column>
      <el-table-column prop="phone" label="手机" width="120">
      el-table-column>
      <el-table-column prop="roleId" label="角色" width="120">
        <template slot-scope="scope">
          <el-tag
              :type="scope.row.roleId === 0 ? 'danger' : (scope.row.roleId === 1 ? 'primary' : 'success')"
              disable-transitions>{{scope.row.roleId === 0 ? '超管' : (scope.row.roleId === 1 ? '管理' : '普通')}}el-tag>
        template>
      el-table-column>
      <el-table-column prop="operate" label="操作">
        <template slot-scope="scope">
          <el-button size="small" type="success" >编辑el-button>
          <el-popconfirm
              confirm-button-text='好的'
              cancel-button-text='不用了'
              icon="el-icon-info"
              icon-color="red"
              title="确定删除吗?"
              @confirm="del(scope.row.id)"
              style="margin-left: 5px"
          >
            <el-button size="small" type="danger"  slot="reference">删除el-button>
          el-popconfirm>

        template>

      el-table-column>
    el-table>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    el-pagination>
    <el-dialog
        title="提示"
        :visible.sync="centerDialogVisible"
        width="30%"
        center>
      <el-form ref="form" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="账号" prop="no">
          <el-col :span="20">
            <el-input v-model="form.no">el-input>
          el-col>
        el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-col :span="20">
            <el-input v-model="form.name">el-input>
          el-col>
        el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-col :span="20">
            <el-input v-model="form.age">el-input>
          el-col>
        el-form-item>
        <el-form-item label="密码" prop="password">
          <el-col :span="20">
            <el-input v-model="form.password">el-input>
          el-col>
        el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-col :span="20">
            <el-input v-model="form.phone">el-input>
          el-col>
        el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="form.sex">
            <el-radio label="1">el-radio>
            <el-radio label="0">el-radio>
          el-radio-group>
        el-form-item>
      el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="centerDialogVisible = false">取 消el-button>
    <el-button type="primary" @click="save">确 定el-button>
  span>
    el-dialog>
  div>
template>

<script>
export default {
  name: "UserManager",
  data() {
    let checkAge = (rule, value, callback) => {
      if(value>150){
        callback(new Error('年龄输⼊过⼤'));
      }else{
        callback();
      }
    };
    let checkDuplicate =(rule,value,callback)=>{
      if(this.form.id){
        return callback();
      }
      this.$axios.get(this.$httpUrl+"/user/findByNo?no="+this.form.no).then(res=>res.data).then(res=>{
        if(res.code!=200){
          callback()
        }else{
          callback(new Error('账号已经存在'));
        }
      })
    };

    return {
      tableData: [],
      pageNum:1,
      pageSize:2,
      total:0,
      name:null,
      sex:null,
      sexs:[{
        value: 1,
        label: '男'
      }, {
        value: 0,
        label: '女'
      }],
      centerDialogVisible:false,
      form:{
        id:'',
        no:'',
        name:'',
        password:'',
        age:'',
        phone:'',
        sex:'0',
        roleId:'2'
      },
      rules: {
        name: [
          {required: true, message: '请输入名字', trigger: 'blur'},
          {min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur'}
        ],
        no: [
          {required: true, message: '请输入账号', trigger: 'blur'},
          {min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur'},
          {validator:checkDuplicate,trigger: 'blur'}

        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur'}
        ],
        age: [
          {required: true, message: '请输⼊年龄', trigger: 'blur'},
          {min: 1, max: 3, message: '⻓度在 1 到 3 个位', trigger: 'blur'},
          {pattern: /^([1-9][0-9]*){1,3}$/,message: '年龄必须为正整数字',trigger: "blur"},
          {validator:checkAge,trigger: 'blur'}
        ],
        phone: [
          {required: true,message: "⼿机号不能为空",trigger: "blur"},
          {pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输⼊正确的⼿机号码", trigger:
                "blur"}
        ]
      }
    }
  },
  methods:{
    resetForm(){
      this.$refs.form.resetFields();
    },
    mod(row){

      this.centerDialogVisible=true
      this.$nextTick(()=> {
        this.form.id = row.id
        this.form.no = row.no
        this.form.name = row.name
        this.form.password = ''
        this.form.sex = row.sex + ''
        this.form.age = row.age + ''
        this.form.phone = row.phone
        this.form.roleId = row.roleId
      })
    },
    add(){
      this.centerDialogVisible=true
      this.$nextTick(
          ()=>{
            this.resetForm();
          }
      )
    },
    doSave(){
      this.$axios.post(this.$httpUrl+'/user/save',this.form).then(res=>res.data).then(res=>{
            console.log(res)
            if(res.code==200){
              this.$message({
                message: '操作成功',
                type: 'success'
              });
              this.centerDialogVisible=false
              this.loadPost()

            }else {
              this.$message({
                message: '操作失败',
                type: 'error'
              });            }
          }

      )
    },
    doMod(){
      this.$axios.post(this.$httpUrl+'/user/update',this.form).then(res=>res.data).then(res=>{
            console.log(res)
            if(res.code==200){
              this.$message({
                message: '操作成功',
                type: 'success'
              });
              this.centerDialogVisible=false
              this.loadPost()

            }else {
              this.$message({
                message: '操作失败',
                type: 'error'
              });            }
          }

      )
    },
    del(id){
      this.$axios.get(this.$httpUrl+'/user/del?id='+id).then(res=>res.data).then(res=>{
            console.log(res)
            if(res.code==200){
              this.$message({
                message: '操作成功',
                type: 'success'
              });
              this.loadPost()

            }else {
              this.$message({
                message: '操作失败',
                type: 'error'
              });            }
          }

      )
    },
    save(){
      this.$refs.form.validate((valid) => {
        if (valid) {
          //alert('submit!');

          if(this.form.id){
            this.doMod();
          }else {
            this.doSave();
          }


        } else {
          console.log('error submit!!');
          return false;
        }
      });


    },
    handleSizeChange(val) {
      console.log(`每页 ${val}`);
      this.pageNum=1
      this.pageSize=val
      this.loadPost()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum=val
      this.loadPost()
    },
    loadGet(){
      this.$axios.get(this.$httpUrl+'/user/get').then(res=>res.data).then(res=>{
            console.log(res)
          }

      )
    },
    resetParam(){
      this.name=null
      this.sex=null
    },
    loadPost(){
      this.$axios.post(this.$httpUrl+'/user/selectPage',{
        size:this.pageSize,
        number:this.pageNum,
        param:{
          name:this.name,
          sex:this.sex,
          roleId: '2'
        }
      }).then(res=>res.data).then(res=>{
            console.log(res)
            if(res.code==200){
              this.tableData=res.data
              this.total=res.total
            }else {
              alert("失败");
            }
          }

      )
    }
  },
  beforeMount() {
    //this.loadGet();
    this.loadPost();
  }
}
script>

<style scoped>

style>

你可能感兴趣的:(Mac开发,vue.js,javascript,前端)