用vue实现简单的增删改查

封装一个增删改查的基本操作,在vue项目的src文件夹下再建一个文件夹untils,并在它下面新建一个js文件,名为db.js(可随便取名)

/**
 * 获取所有的数据
 */
export function getAllpeople () {
  var people = []
  if (localStorage.getItem('people')) {
    people = JSON.parse(localStorage.getItem('people'))
  }
  return people
}

/**
 * 保存,增
 * @param {*} person
 */
export function save (person) {
  var people = getAllpeople()
  people.push(person)
  localStorage.setItem('people', JSON.stringify(people))
}

/**
 * 根据id删除
 * @param {*} id
 */

export function deleteOne (id) {
  var people = getAllpeople()
  var index = people.findIndex(function (person) {
    return person.id === id
  })

  people.splice(index, 1)
  localStorage.setItem('people', JSON.stringify(people))
}

/**
 * 根据id修改数据
 * @param {*} id
 * @param {*} person
 */
export function update (id, person) {
  var people = getAllpeople()
  // 找到id符合条件的索引

  var index = people.findIndex(function (item) {
    return item.id === id
  })
  person.id = id * 1
  people[index] = person
  localStorage.setItem('people', JSON.stringify(people))
}

/**
 * 查询id符合条件的一条记录
 * @param {*} id
 */

export function findOne (id) {
  var people = getAllpeople()

  return people.find(function (item) {
    return item.id === id
  })
}

新建一个List.vue,列表页,用来展示数据,新增之后以及查询之后都在本页面显示。使用计算属性或者使watch监听,都能实现查询之后的数据展示。

<template>
  <div class="list">
    <div class="panel panel-info">
      <div class="panel-heading">
        <h3 class="panel-title">列表页</h3>
      </div>

      <form class="form-inline">
        <div class="form-group">
          <label for="key">关键字</label>
          <input
            type="email"
            id="key"
            class="form-control"
            v-model="keysword"
            placeholder="请输入姓名和QQ"
          />
        </div>
      </form>

      <router-link class="btn btn-primary" :to="{name: 'editor'}">新增</router-link>
      <div class="panel-body">
        <table class="table table-striped table-hover">
          <thead>
            <tr>
              <th>序号</th>
              <th>姓名</th>
              <th>手机号</th>
              <th>QQ</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(person,index) in filterList" :key="person.id">
              <!-- <tr v-for="(person,index) in newList" :key="person.id"> -->
              <td>{{index+1}}</td>
              <td>{{person.name}}</td>
              <td>{{person.phone}}</td>
              <td>{{person.qq}}</td>
              <td>
                <router-link
                  :to="{name:'editor',query:{id:person.id}}"
                  class="btn btn-small btn-info"
                >修改</router-link>
                <button @click="delOne(person.id)" class="btn btn-small btn-danger">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import { getAllpeople, deleteOne } from '../utils/db'

export default {
  name: 'list',
  data () {
    return {
      list: [],
      keysword: '',
      newList: []
    }
  },
  created () {
    this.list = getAllpeople()
    this.newList = this.list
  },
  methods: {
    delOne (id) {
      if (confirm('是否确认删除?')) {
        deleteOne(id)
        this.list = getAllpeople()
      }
    }

  },
  computed: {
    filterList () {
      return this.list.filter(
        item =>
          item.name.indexOf(this.keysword) > -1 ||
            item.qq.indexOf(this.keysword) > -1
      )
    }
  }

  // watch: {
  //   keysword: function () {
  //     if (this.keysword !== '') {
  //       this.newList = this.list.filter(
  //         item =>
  //           item.name.indexOf(this.keysword) > -1 ||
  //           item.qq.indexOf(this.keysword) > -1
  //       )
  //     } else {
  //       this.newList = this.list
  //     }
  //   }
  // }

}
</script>

<style>

.form-inline{float: left;margin-right:20px;}
.btn-primary{float: left}
</style>

新建一个Editor.vue用来增加和修改数据

<template>
  <div class="editor">
    <div class="panel panel-info">
      <div class="panel-heading">
        <h3 class="panel-title">编辑</h3>
      </div>
      <div class="panel-body">
        <div>
          <div class="form-group">
            <label for>姓名</label>
            <input type="text" class="form-control" v-model="person.name" placeholder=" 请输入姓名" />
          </div>
          <div class="form-group">
            <label for>手机号</label>
            <input type="text" class="form-control" v-model="person.phone" placeholder=" 请输入手机号" />
          </div>
          <div class="form-group">
            <label for>QQ</label>
            <input type="text" class="form-control" v-model="person.qq" placeholder=" 请输入QQ" />
          </div>

          <button type="submit" class="btn btn-primary" @click="saveHandle">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
// eslint-disable-next-line no-unused-vars
import { getAllpeople, save, update, findOne } from '../utils/db'
export default {
  data () {
    return {
      person: {},
      isEdit: false,
      id: ''
    }
  },
  created () {
    if (this.$route.query.id) {
      this.isEdit = true
      this.id = this.$route.query.id
      this.person = findOne(this.id)
    }
  },
  methods: {
    saveHandle () {
      if (this.person.name && this.person.qq) {
        if (this.isEdit) {
          update(this.id, this.person)
        } else {
          this.person.id = Date.now()
          save(this.person)
        }
        // console.log(getAllpeople())
        this.$router.push({
          name: 'list'
        })
      } else {
        alert('请输入用户名和QQ号')
      }
    }
  }
}

</script>

路由设置,在router文件夹下的index.js中写下列代码。(创建vue脚手架的时候直接选上router)

import Vue from 'vue'
import VueRouter from 'vue-router'
import List from '../views/List.vue'
import Editor from '../views/Editor.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'list',
    component: List
  },
  {
    path: '/editor',
    name: 'editor',
    component: Editor
  }
]

const router = new VueRouter({
  routes
})

export default router

版权声明:本文为qq_39288987原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。