nodejs vue-element-admin (實(shí)訓(xùn)5糖耸、6)

nodejs vue-element-admin (實(shí)訓(xùn)5)

目標(biāo):創(chuàng)建班級(jí)管理模塊(學(xué)生和班級(jí)俐筋、學(xué)院伪煤、學(xué)校關(guān)聯(lián)起來)
一坊夫、后臺(tái)三步驟:
1厉熟、打開projectName文件抹估,在/db/models目錄下創(chuàng)建student.js文件廉丽,接著文件操作:/db/models/student.js

const mongoose = require('mongoose')
const Schema = mongoose.Schema
const feld={
    name: String,
    age: Number,
    student_number:Number,
    gender:String,
    school : { type: Schema.Types.ObjectId, ref: 'School' },
    academy : { type: Schema.Types.ObjectId, ref: 'Academy' },
    classs : { type: Schema.Types.ObjectId, ref: 'Classs' }

}
//自動(dòng)添加更新時(shí)間創(chuàng)建時(shí)間:
let personSchema = new mongoose.Schema(feld, {timestamps: {createdAt: 'created', updatedAt: 'updated'}})
module.exports= mongoose.model('Student',personSchema)

2倦微、找到projectName下的routes目錄,創(chuàng)建student.js文件:/routes/student.js

const router = require('koa-router')()
let Model = require("../db/models/student");
router.prefix('/student')

router.get('/', function (ctx, next) {
    ctx.body = 'this is a users response!'
})

router.post('/add', async function (ctx, next) {
    console.log(ctx.request.body)
    let model = new Model(ctx.request.body);
    model = await model.save();
    console.log('user',model)
    ctx.body = model
})

router.post('/find', async function (ctx, next) {
    let models = await Model.
    find({}).populate('classs').populate('academy').populate('school')
    ctx.body = models
})

router.post('/get', async function (ctx, next) {
    // let users = await User.
    // find({})
    console.log(ctx.request.body)
    let model = await Model.find(ctx.request.body)
    console.log(model)
    ctx.body = model
})

router.post('/update', async function (ctx, next) {
    console.log(ctx.request.body)
    let pbj = await Model.update({ _id: ctx.request.body._id }, ctx.request.body);
    ctx.body = pbj
})
router.post('/delete', async function (ctx, next) {
    console.log(ctx.request.body)
    await Model.remove({ _id: ctx.request.body._id });
    ctx.body = 'shibai '
})
module.exports = router

3.在根目錄下/app.js中掛載路由:

const classs= require('./routes/student')
app.use(student.routes(), student.allowedMethods())

二正压、前臺(tái)三步驟:
打開vue-admin-template-master文件欣福,在/src/views目錄下創(chuàng)建一個(gè)student模塊,/src/views/student
并在student目錄下創(chuàng)建vue文件焦履。

1./src/views/student/editor.vue為編輯文件劣欢,用于創(chuàng)建班級(jí)記錄棕诵;

<template>
  <div class="dashboard-container">
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="所屬學(xué)校">
        <el-select v-model="form.school" placeholder="請(qǐng)選擇" @change="schoolChange">
          <el-option
            v-for="item in schools"
            :key="item._id"
            :label="item.name"
            :value="item._id">
          </el-option>
        </el-select>
      </el-form-item>
      <!--      編輯框:學(xué)院選擇列表-->
      <el-form-item label="所屬學(xué)院">
        <el-select v-model="form.academy" placeholder="請(qǐng)選擇">
          <el-option
            v-for="item in academys"
            :key="item._id"
            :label="item.name"
            :value="item._id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="所屬班級(jí)">
        <el-select v-model="form.classs" placeholder="請(qǐng)選擇">
          <el-option
            v-for="item in classs"
            :key="item._id"
            :label="item.name"
            :value="item._id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用戶名">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="年齡">
        <el-input v-model="form.age"></el-input>
      </el-form-item>
      <el-form-item label="學(xué)號(hào)">
        <el-input v-model="form.student_number"></el-input>
      </el-form-item>
      <el-form-item label="性別">
        <el-input v-model="form.gender"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即創(chuàng)建</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'

  export default {
    name: 'student',
    computed: {
      ...mapGetters([
        'name'
      ])
    },
    data(){
      return{
        schools:[],
        academys:[],
        classs:[],
        options: [
        ],
        apiModel:'student',
        form:{}
      }
    },
    methods:{
      onSubmit(){
        if(this.form._id){
          this.$http.post(`/api/${this.apiModel}/update`,this.form).then(res => {
            console.log('bar:', res)
            this.$router.push({path:this.apiModel})
            this.form={}
          })
        }else
        {
          this.$http.post('/api/'+this.apiModel+'/add',this.form).then(res => {
            console.log('bar:', res)
            this.$router.push({path:this.apiModel})
            this.form={}
          })
        }
      },
      schoolChange(val1){
        //顯示學(xué)院選擇欄目
        this.$http.post('/api/academy/get',{school:val1}).then(res => {
          if(res&&res.length>0){
            this.academys = res
            console.log('res:', res)
          }
        })
      }
    },

    mounted() {
      if(this.$route.query._id){
        this.$http.post('/api/'+this.apiModel+'/get',{_id:this.$route.query._id}).then(res => {
          if(res&&res.length>0){
            this.form = res[0]
            this.schoolChange(this.form.school)
          }
        })
      }

      //顯示學(xué)校選擇欄目
      this.$http.post('/api/school/find').then(res => {
        if(res&&res.length>0){
          this.schools = res
          console.log('res:', res)
        }
      })
      //顯示班級(jí)欄目
      this.$http.post('/api/classs/find').then(res => {
        if(res&&res.length>0){
          this.classs = res
          console.log('res:', res)
        }
      })
    }
  }
</script>

<style lang="scss" scoped>
  .dashboard {
    &-container {
      margin: 30px;
    }
    &-text {
      font-size: 30px;
      line-height: 46px;
    }
  }
</style>

2./src/views/student/index.vue為目錄文件,用于顯示結(jié)果凿将;

<template>
  <div class="dashboard-container">
    <el-table
      :data="users"
      style="width: 100%"
      :row-class-name="tableRowClassName">
      <el-table-column
        prop="name"
        label="名字"
        width="180">
      </el-table-column>
      <el-table-column
        prop="age"
        label="年齡"
        width="180">
      </el-table-column>
      <el-table-column
        prop="student_number"
        label="學(xué)號(hào)">
      </el-table-column>
      <el-table-column
        prop="gender"
        label="性別">
      </el-table-column>
      <!--      列表添加項(xiàng)目
-->
      <el-table-column
        prop="school"
        label="學(xué)校名稱"
        width="180">
        <template slot-scope="scope" >
          <span class="" v-if="scope.row.school">
            <el-tag
              :type="scope.row.school.name === '深圳信息職業(yè)技術(shù)學(xué)院' ? 'primary' : 'success'"
              disable-transitions>{{scope.row.school.name}}</el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="academy"
        label="學(xué)院名稱"
        width="180">
        <template slot-scope="scope" >
          <span class="" v-if="scope.row.academy">
            <el-tag
              :type="scope.row.academy.name === '軟件學(xué)院' ? 'primary' : 'success'"
              disable-transitions>{{scope.row.academy.name}}</el-tag>
          </span>

        </template>
      </el-table-column>

      <el-table-column
        prop="classs"
        label="班級(jí)名稱"
        width="180">
        <template slot-scope="scope" >
          <span class="" v-if="scope.row.classs">
            <el-tag
              :type="scope.row.classs.name === '18軟工4-3' ? 'primary' : 'success'"
              disable-transitions>{{scope.row.classs.name}}</el-tag>
          </span>

        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)">編輯
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">刪除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'

  export default {
    name: 'student',
    computed: {
      ...mapGetters([
        'name'
      ])
    },
    data() {
      return {
        apiModel:'student',
        users: {}
      }
    },
    methods: {
      onSubmit() {
        console.log(123434)
      },
      handleEdit(index, item) {
        this.$router.push({ path: '/'+this.apiModel+'/editor', query: {_id:item._id} })
      },
      handleDelete(index, item) {
        this.$http.post('/api/'+this.apiModel+'/delete', item).then(res => {
          console.log('res:', res)
          this.findUser()
        })

      },
      findUser(){
        this.$http.post('/api/'+this.apiModel+'/find', this.user).then(res => {
          console.log('res:', res)
          this.users = res
        })
      }
    },
    mounted() {
      this.findUser()
    }
  }
</script>

<style lang="scss" scoped>
  .dashboard {
    &-container {
      margin: 30px;
    }

    &-text {
      font-size: 30px;
      line-height: 46px;
    }
  }
</style>

3.在/src/router/index.js中添加路由:

 {
    path: '/student',
    component: Layout,
    meta: { title: '學(xué)生管理', icon: 'example' },
    redirect: '/student',
    children: [{
      path: 'student',
      name: 'student',
      component: () => import('@/views/student/index'),
      meta: { title: '學(xué)生管理', icon: 'user' }
    },
      {
        path: 'editor',
        name: 'editor',
        component: () => import('@/views/student/editor'),
        meta: { title: '添加學(xué)生', icon: 'user' }
      }]
  },

nodejs vue-element-admin (實(shí)訓(xùn)6)

目標(biāo):創(chuàng)建班級(jí)管理模塊(老師和學(xué)院校套、學(xué)校關(guān)聯(lián)起來)
一、后臺(tái)三步驟:
1牧抵、打開projectName文件笛匙,在/db/models目錄下創(chuàng)建teacher.js文件,/db/models/teacher
接著文件操作:

const mongoose = require('mongoose')
const Schema= mongoose.Schema
const feld={
    name: String,
    age: String,
    //人物標(biāo)簽
    level:String,
    gender:String,
    school : { type: Schema.Types.ObjectId, ref: 'School' },
    academy : { type: Schema.Types.ObjectId, ref: 'Academy' }
}
//自動(dòng)添加更新時(shí)間創(chuàng)建時(shí)間:
let personSchema = new mongoose.Schema(feld, {timestamps: {createdAt: 'created', updatedAt: 'updated'}})
module.exports= mongoose.model('Teacher',personSchema)

2犀变、找到projectName下的routes目錄妹孙,創(chuàng)建teacher.js文件:/routes/teacher.js

const router = require('koa-router')()
let Model = require("../db/models/teacher");
router.prefix('/teacher')

router.get('/', function (ctx, next) {
    ctx.body = 'this is a users response!'
})

router.post('/add', async function (ctx, next) {
    console.log(ctx.request.body)
    let model = new Model(ctx.request.body);
    model = await model.save();
    console.log('user',model)
    ctx.body = model
})

router.post('/find', async function (ctx, next) {
    let models = await Model.
    find({}).populate('academy').populate('school')
    ctx.body = models
})

router.post('/get', async function (ctx, next) {
    // let users = await User.
    // find({})
    console.log(ctx.request.body)
    let model = await Model.find(ctx.request.body)
    console.log(model)
    ctx.body = model
})

router.post('/update', async function (ctx, next) {
    console.log(ctx.request.body)
    let pbj = await Model.update({ _id: ctx.request.body._id }, ctx.request.body);
    ctx.body = pbj
})
router.post('/delete', async function (ctx, next) {
    console.log(ctx.request.body)
    await Model.remove({ _id: ctx.request.body._id });
    ctx.body = 'shibai '
})
module.exports = router


3.在根目錄/app.js中掛載路由:

const teacher= require('./routes/teacher')
app.use(teacher.routes(), teacher.allowedMethods())

二、前臺(tái)三步驟:
打開vue-admin-template-master文件获枝,在/src/views目錄下創(chuàng)建一個(gè)teacher模塊蠢正,/src/views/teacher
并在teacher目錄下創(chuàng)建vue文件。

1./src/views/teacher/editor.vue為編輯文件省店,用于創(chuàng)建班級(jí)記錄嚣崭;

<template>
  <div class="dashboard-container">
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="所屬學(xué)校">
        <el-select v-model="form.school" placeholder="請(qǐng)選擇" @change="schoolChange">
          <el-option
            v-for="item in schools"
            :key="item._id"
            :label="item.name"
            :value="item._id">
          </el-option>
        </el-select>
      </el-form-item>
      <!--      編輯框:學(xué)院選擇列表-->
      <el-form-item label="所屬學(xué)院">
        <el-select v-model="form.academy" placeholder="請(qǐng)選擇">
          <el-option
            v-for="item in academys"
            :key="item._id"
            :label="item.name"
            :value="item._id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用戶名">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="年齡">
        <el-input v-model="form.age"></el-input>
      </el-form-item>
      <el-form-item label="性別">
        <el-input v-model="form.gender"></el-input>
      </el-form-item>
      <el-form-item label="級(jí)別">
        <el-input v-model="form.level"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即創(chuàng)建</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'

  export default {
    name: 'teacher-editor',
    computed: {
      ...mapGetters([
        'name'
      ])
    },
    data(){
      return{
        schools:[],
        academys:[],
        options: [
        ],
        apiModel:'teacher',
        form:{}
      }
    },
    methods:{
      onSubmit(){
        if(this.form._id){
          this.$http.post(`/api/${this.apiModel}/update`,this.form).then(res => {
            console.log('bar:', res)
            this.$router.push({path:this.apiModel})
            this.form={}
          })
        }else
        {
          this.$http.post('/api/'+this.apiModel+'/add',this.form).then(res => {
            console.log('bar:', res)
            this.$router.push({path:this.apiModel})
            this.form={}
          })
        }
      },
      schoolChange(val1){
        //顯示學(xué)院選擇欄目
        this.$http.post('/api/academy/get',{school:val1}).then(res => {
          if(res&&res.length>0){
            this.academys = res
            console.log('res:', res)
          }
        })
      }
    },

    mounted() {
      if(this.$route.query._id){
        this.$http.post('/api/'+this.apiModel+'/get',{_id:this.$route.query._id}).then(res => {
          if(res&&res.length>0){
            this.form = res[0]
            this.schoolChange(this.form.school)
          }
        })
      }

      //顯示學(xué)校選擇欄目
      this.$http.post('/api/school/find').then(res => {
        if(res&&res.length>0){
          this.schools = res
          console.log('res:', res)
        }
      })
    }
  }
</script>

<style lang="scss" scoped>
  .dashboard {
    &-container {
      margin: 30px;
    }
    &-text {
      font-size: 30px;
      line-height: 46px;
    }
  }
</style>


2./src/views/teacher/index.vue為目錄文件,用于顯示結(jié)果懦傍;

<template>
  <div class="dashboard-container">
    <el-table
      :data="users"
      style="width: 100%"
      :row-class-name="tableRowClassName">
      <el-table-column
        prop="name"
        label="名字"
        width="180">
      </el-table-column>
      <el-table-column
        prop="age"
        label="年齡"
        width="180">
      </el-table-column>
      <el-table-column
        prop="level"
        label="等級(jí)">
      </el-table-column>
      <el-table-column
        prop="gender"
        label="性別">
      </el-table-column>
      <!--      列表添加項(xiàng)目
-->
      <el-table-column
        prop="school"
        label="學(xué)校名稱"
        width="180">
        <template slot-scope="scope" >
          <span class="" v-if="scope.row.school">
            <el-tag
              :type="scope.row.school.name === '深圳信息職業(yè)技術(shù)學(xué)院' ? 'primary' : 'success'"
              disable-transitions>{{scope.row.school.name}}</el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="academy"
        label="學(xué)院名稱"
        width="180">
        <template slot-scope="scope" >
          <span class="" v-if="scope.row.academy">
            <el-tag
              :type="scope.row.academy.name === '軟件學(xué)院' ? 'primary' : 'success'"
              disable-transitions>{{scope.row.academy.name}}</el-tag>
          </span>

        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)">編輯
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">刪除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'

  export default {
    name: 'teacher',
    computed: {
      ...mapGetters([
        'name'
      ])
    },
    data() {
      return {
        apiModel:'teacher',
        users: {}
      }
    },
    methods: {
      onSubmit() {
        console.log(123434)
      },
      handleEdit(index, item) {
        this.$router.push({ path: '/'+this.apiModel+'/editor', query: {_id:item._id} })
      },
      handleDelete(index, item) {
        this.$http.post('/api/'+this.apiModel+'/delete', item).then(res => {
          console.log('res:', res)
          this.findUser()
        })

      },
      findUser(){
        this.$http.post('/api/'+this.apiModel+'/find', this.user).then(res => {
          console.log('res:', res)
          this.users = res
        })
      }
    },
    mounted() {
      this.findUser()
    }
  }
</script>

<style lang="scss" scoped>
  .dashboard {
    &-container {
      margin: 30px;
    }

    &-text {
      font-size: 30px;
      line-height: 46px;
    }
  }
</style>


3.在/src/router/index.js中添加路由:

  {
    path: '/teacher',
    component: Layout,
    meta: { title: '老師管理', icon: 'example' },
    redirect: '/teacher',
    children: [{
      path: 'teacher',
      name: 'teacher',
      component: () => import('@/views/teacher'),
      meta: { title: '老師管理', icon: 'user' }
    },
      {
        path: 'editor',
        name: 'editor',
        component: () => import('@/views/teacher/editor'),
        meta: { title: '添加老師', icon: 'user' }
      }]
  },
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末雹舀,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子粗俱,更是在濱河造成了極大的恐慌说榆,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,454評(píng)論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件寸认,死亡現(xiàn)場(chǎng)離奇詭異签财,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)偏塞,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,553評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門荠卷,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人烛愧,你說我怎么就攤上這事油宜。” “怎么了怜姿?”我有些...
    開封第一講書人閱讀 157,921評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵慎冤,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我沧卢,道長(zhǎng)蚁堤,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,648評(píng)論 1 284
  • 正文 為了忘掉前任但狭,我火速辦了婚禮披诗,結(jié)果婚禮上撬即,老公的妹妹穿的比我還像新娘。我一直安慰自己呈队,他們只是感情好剥槐,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,770評(píng)論 6 386
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著宪摧,像睡著了一般粒竖。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上几于,一...
    開封第一講書人閱讀 49,950評(píng)論 1 291
  • 那天蕊苗,我揣著相機(jī)與錄音,去河邊找鬼沿彭。 笑死朽砰,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的喉刘。 我是一名探鬼主播瞧柔,決...
    沈念sama閱讀 39,090評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼饱搏!你這毒婦竟也來了非剃?” 一聲冷哼從身側(cè)響起置逻,我...
    開封第一講書人閱讀 37,817評(píng)論 0 268
  • 序言:老撾萬榮一對(duì)情侶失蹤推沸,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后券坞,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體鬓催,經(jīng)...
    沈念sama閱讀 44,275評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,592評(píng)論 2 327
  • 正文 我和宋清朗相戀三年恨锚,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了宇驾。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,724評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡猴伶,死狀恐怖课舍,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情他挎,我是刑警寧澤筝尾,帶...
    沈念sama閱讀 34,409評(píng)論 4 333
  • 正文 年R本政府宣布,位于F島的核電站办桨,受9級(jí)特大地震影響筹淫,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜呢撞,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,052評(píng)論 3 316
  • 文/蒙蒙 一损姜、第九天 我趴在偏房一處隱蔽的房頂上張望饰剥。 院中可真熱鬧,春花似錦摧阅、人聲如沸汰蓉。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,815評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽古沥。三九已至,卻和暖如春娇跟,著一層夾襖步出監(jiān)牢的瞬間岩齿,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,043評(píng)論 1 266
  • 我被黑心中介騙來泰國(guó)打工苞俘, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留盹沈,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,503評(píng)論 2 361
  • 正文 我出身青樓吃谣,卻偏偏與公主長(zhǎng)得像乞封,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子岗憋,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,627評(píng)論 2 350

推薦閱讀更多精彩內(nèi)容