Vue+Node(express)+ ElementUI实现各种功能(一)

阳福
2023-12-01

一.首先使用ElementUI实现后台的增删改查
用vue-cli先搭建一个项目admin,再创建一个文件夹,命名为serve,里面放自己写的接口数据和连接mongodb数据库等

在serve文件夹中操作

第一步

npm init -y 先初始化一个package.json
再安装express,mongoose,cors
npm i express   
npm i mongoose
npm i cors  //跨域

第二步:建立一个plugins文件,里面建立一个db.js,导入数据库

  module.exports =app=>{
  const mongoose =require('mongoose')
  mongoose.connect('mongodb://127.0.0.1:27017/store',{
  //store名字可随便取,会存到你的mongo数据库
    useNewUrlParser:true //解析URL
  })
}

第三步:建立一个models文件,里面建立一个Category.js,作为编译模版,操作数据库

 const mongoose =require('mongoose')
 const schema =new mongoose.Schema({
  name:{type:String}
})
module.exports = mongoose.model('Category',schema)

第四步:建立一个routes文件,里面在建立一个admin文件,admin里面再建立一个index.js,用来存放接口数据,更改数据,删除数据等请求

module.exports =app =>{
  const express = require('express')
  const router = express.Router({
  mergeParams:true //合并url参数
}) //引入路由
  //创建分类接口
 router.post('/',async(req,res)=>{
 const model =  await req.Model.create(req.body)
 res.send(model)
})
//更新数据
router.put('/:id',async(req,res)=>{
const model =  await  req.Model.findByIdAndUpdate(req.params.id,req.body)
res.send(model)
})
//删除数据
router.delete('/:id',async(req,res)=>{
await req.Model.findByIdAndDelete(req.params.id,req.body)
res.send({
  success:true
})
})
//详情数据接口
router.get('/:id',async(req,res)=>{
const model =  await req.Model.findById(req.params.id)
res.send(model)
})
}
app.use('/admin/api/rest/:resource',async(req,res,next)=>{
const modelName = require('inflection').classify(req.params.resource) //转大小写类名
req.Model = require(`../../models/${modelName}`)
next()
},router) //动态参数
这一步还需要在终端下一个插件
npm i inflection

第五步:建立一个主index.js文件,引入各类和使用

const express = require('express')
const app =express()
app.use(require('cors')())
app.use(express.json())
require('./plugins/db')(app)
require('./routes/admin')(app)
app.listen(3000,()=>{

}) //通过3000端口访问

前端页面,在admin中操作

第一步:安装element-ui和路由,axios插件

npm i element-ui -S
npm i router -S
npm i axios -S
然后在main.js中引入
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
Vue.use(ElementUI);
import http from "./http";
Vue.prototype.$http = http;

第二步:新建一个http.js文件,放网络请求

import axios from "axios";

const http = axios.create({
  baseURL: "http://localhost:3000/admin/api"
});

export default http;

第三步:在views文件中建立三个vue文件,Main.vue,CategoryEdit.vue,CategoryList.vue

Main.vue中

<template>
  <el-container style="height: 100vh;">
    <el-aside width="200px" style="background-color: rgb(238, 241, 246)">
      <el-menu router :default-openeds="['1', '3']">
        <el-submenu index="1">
          <template slot="title"
            ><i class="el-icon-message"></i>内容管理</template
          >
          <el-menu-item-group>
            <template slot="title">分类</template>
            <el-menu-item index="/categories/create">新建分类</el-menu-item>
            <el-menu-item index="/categories/list">分类列表</el-menu-item>
          </el-menu-item-group>
        </el-submenu>
      </el-menu>
    </el-aside>

    <el-container>
      <el-header style="text-align: right; font-size: 12px">
        <el-dropdown>
          <i class="el-icon-setting" style="margin-right: 15px"></i>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item>查看</el-dropdown-item>
            <el-dropdown-item>新增</el-dropdown-item>
            <el-dropdown-item>删除</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <span>王小虎</span>
      </el-header>

      <el-main>
        <router-view></router-view>
      </el-main>
    </el-container>
  </el-container>
   </template>

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

.el-aside {
  color: #333;
}
</style>

<script>
export default {
  data() {
    const item = {
      date: "2016-05-02",
      name: "王小虎",
      address: "上海市普陀区金沙江路 1518 弄"
    };
    return {
      tableData: Array(20).fill(item)
    };
  }
};
</script>

CategoryEdit.vue中

<template>
  <div>
    <h1>{{id ?'编辑':'新建'}}分类</h1>
    <el-form label-width="120px" @submit.native.prevent="save">
      <el-form-item label="名称">
        <el-input v-model="model.name"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  props: {
    id: {}
  },
  data() {
    return {
      model: {},
    };
  },
  methods: {
    async save() {
      let res
      if(this.id){//有id就修改
     res = await this.$http.put(`rest/categories/${this.id}`, this.model);
      }else{//如果没有id就添加
     res = await this.$http.post("rest/categories", this.model);
      }
     
      this.$router.push("/categories/list");
      this.$message({
        type: "success",
        message: "保存成功"
      });
    },
    async fetch(){
      const res = await this.$http.get(`rest/categories/${this.id}`)
      this.model  =res.data
    },
   
},
  created() {
    this.id && this.fetch()
  },
};
</script>

<style></style>

CategoryList.vue中

 <template>
  <div>
    <h1>分类列表</h1>
    <el-table :data="items">
      <el-table-column prop="_id" label="ID" width="240"></el-table-column>
      <el-table-column prop="name" label="分类名称"></el-table-column>
      <el-table-column fixed="right" label="操作" width="180">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="$router.push(`/categories/edit/${scope.row._id}`)"
            >编辑</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="remove(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: []
    };
  },
  methods: {
    async fetch() {
      const res = await this.$http.get("rest/categories");
      this.items = res.data;
    },
    async remove(row){
      this.$confirm(`是否确定要删除分类 "${row.name}"`,'提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const res = await this.$http.delete(`rest/categories/${row._id}`)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.fetch()
        })       
        
    }
  },
  created() {
    this.fetch();
  }
};
</script>

<style></style>

第四步:在路由js文件中引入这些组件

   import Vue from "vue";
import VueRouter from "vue-router";
import Main from "../views/Main.vue";
import CategoryEdit from "../views/CategoryEdit.vue";
import CategoryList from "../views/CategoryList.vue";


Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "main",
    component: Main,
    children: [
      {
        path: "/categories/create",
        component: CategoryEdit
      },
      {
        path: "/categories/edit/:id",
        component: CategoryEdit,
        props: true //把所以参数都注入到CategoryEdit里面
      },
      {
        path: "/categories/list",
        component: CategoryList
      },
    ]
  }
];

const router = new VueRouter({
  routes
});

export default router;

第五步:在APP.vue中操作

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

<style lang="less">
html,
body {
  padding: 0;
  margin: 0;
}
</style>

完事,下一篇博客讲上一级和上传图片等

 类似资料: