一、新增

1、定义api

src/api/edu/teacher.js

  1. save(teacher) {
  2. return request({
  3. url: api_name,
  4. method: 'post',
  5. data: teacher
  6. })
  7. }

2、初始化组件

src/views/edu/teacher/form.vue
html

<template>
  <div class="app-container">
    <el-form label-width="120px">
      <el-form-item label="讲师名称">
        <el-input v-model="teacher.name"/>
      </el-form-item>
      <el-form-item label="讲师排序">
        <el-input-number v-model="teacher.sort" controls-position="right" min="0"/>
      </el-form-item>
      <el-form-item label="讲师头衔">
        <el-select v-model="teacher.level" clearable placeholder="请选择">
          <!--
            数据类型一定要和取出的json中的一致,否则没法回填
            因此,这里value使用动态绑定的值,保证其数据类型是number
          -->
          <el-option :value="1" label="高级讲师"/>
          <el-option :value="2" label="首席讲师"/>
        </el-select>
      </el-form-item>
      <el-form-item label="讲师资历">
        <el-input v-model="teacher.career"/>
      </el-form-item>
      <el-form-item label="讲师简介">
        <el-input v-model="teacher.intro" :rows="10" type="textarea"/>
      </el-form-item>
      <!-- 讲师头像:TODO -->
      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate">保存</el-button>
      </el-form-item>
    </el-form>
  </div>

</template>

js

<script>
export default {
  data() {
    return {
      teacher: {
        name: '',
        sort: 0,
        level: 1,
        career: '',
        intro: '',
        avatar: ''
      },
      saveBtnDisabled: false // 保存按钮是否禁用,
    }
  },


  methods: {


    saveOrUpdate() {
      this.saveBtnDisabled = true
      this.saveData()
    },


    // 保存
    saveData() {


    }


  }

}
</script>

3、实现新增功能

引入teacher api模块

import teacher from '@/api/edu/teacher'

完善save方法

 // 保存
 saveData() {
   teacher.save(this.teacher).then(response => {
     return this.$message({
       type: 'success',
       message: '保存成功!'
     })
   }).then(resposne => {
     this.$router.push({ path: '/edu/teacher' })
   }).catch((response) => {
     // console.log(response)
     this.$message({
       type: 'error',
       message: '保存失败'
     })
   })
    }

二、回显

1、定义api

src/api/edu/teacher.js

getById(id) {
 return request({
     url: `${api_name}/${id}`,
     method: 'get'
 })
}

2、组件中调用api

methods中定义fetchDataById

// 根据id查询记录
fetchDataById(id) {
 teacher.getById(id).then(response => {
     this.teacher = response.data.item
 }).catch((response) => {
     this.$message({
         type: 'error',
         message: '获取数据失败'
     })
 })
}

3、页面渲染前调用fetchDataById

created() {
  console.log('created')
  if (this.$route.params && this.$route.params.id) {
    const id = this.$route.params.id
    this.fetchDataById(id)
  }
}

三、更新

1、定义api

updateById(teacher) {
  return request({
      url: `${api_name}/${teacher.id}`,
      method: 'put',
      data: teacher
  })
}

2、组件中调用api

methods中定义updateData

// 根据id更新记录
updateData() {
 this.saveBtnDisabled = true
 teacher.updateById(this.teacher).then(response => {
     return this.$message({
         type: 'success',
         message: '修改成功!'
     })
 }).then(resposne => {
     this.$router.push({ path: '/edu/teacher' })
 }).catch((response) => {
     // console.log(response)
     this.$message({
         type: 'error',
         message: '保存失败'
     })
 })
}

3、完善saveOrUpdate方法

saveOrUpdate() {
  this.saveBtnDisabled = true
  if (!this.teacher.id) {
      this.saveData()
  } else {
      this.updateData()
  }
}

四、存在问题

vue-router导航切换 时,如果两个路由都渲染同个组件,组件会重(chong)用,

组件的生命周期钩子(created)不会再被调用, 使得组件的一些数据无法根据 path的改变得到更新
因此:
1、我们可以在watch中监听路由的变化,当路由变化时,重新调用created中的内容
2、在init方法中我们判断路由的变化,如果是修改路由,则从api获取表单数据,
如果是新增路由,则重新初始化表单数据

<script>

import teacher from '@/api/edu/teacher'

  const defaultForm = {
  name: '',
  sort: 0,
  level: '',
  career: '',
  intro: '',
  avatar: ''
  }

  export default {
  data() {
    return {
      teacher: defaultForm,
      saveBtnDisabled: false // 保存按钮是否禁用,
    }
  },


  watch: {
    $route(to, from) {
      console.log('watch $route')
      this.init()
    }
  },


  created() {
    console.log('created')
    this.init()
  },


  methods: {


    init() {
      if (this.$route.params && this.$route.params.id) {
        const id = this.$route.params.id
        this.fetchDataById(id)
      } else {
        // 使用对象拓展运算符,拷贝对象,而不是引用,
        // 否则新增一条记录后,defaultForm就变成了之前新增的teacher的值
        this.teacher = { ...defaultForm }
      }
    },


  ......
   }

  }
</script>