- 并且在src-manage-components文件夹中复制ads文件夹,并且改名为books
- 在后台资源管理处加上book菜单,添加新增书籍,显示书籍和管理书籍的接口,在Home.vue页面处保存,则能显示菜单并且刷新。此时显示的页面是ads的内容,因为books里面是ads的内容。
- 在src-manage-components-books-index.vue文件第5行修改顶部菜单栏的type为Book。此时保存,点击顶部add的按键将没有反应。
12<TopBar type="books"></TopBar>
- 在src-manage-components-common-TopBar.vue文件第10行添加顶部菜单栏对应Book的菜单。
1234<div v-else-if="type === 'books'"><el-button type="primary" size="small" plain round @click="addBooks"><i class="fa fa-fw fa-plus"></i></el-button></div>
在该页面152行加入对应的addBook方法。
12345678addBooks() {this.$store.dispatch('booksInfoForm', {edit: false,formData:{}});this.$router.push('/addBooks');},然后在src-manage-components-common-Pagination.vue的75行添加对应的Pagination的样式:
123456} else if (this.pageType === 'books') {this.$store.dispatch('getBooksList', {current: val});} - 在src-manage-store-getters.js中的第7行添加bookInfoForm的说明,对应上面addBooks方法第二句调用的内容:
1234booksList: state => state.books.list,booksInfoForm: state => state.books.infoFormState,booksItemForm: state => state.books.itemFormState,
- 在src-manage-store-mutations.js的第287行添加books的state初始化的内容,目前暂定books的数据库和ads一样,所以里面的内容先不修改,后期还是要改的:
12345678910111213141516171819202122232425262728293031books: {list: {pageInfo: {},docs: []},infoFormState: {edit: false,formData: {name: '',type: '1',height: '',comments: '',items: [],state: true,carousel: true}},itemFormState: {show: false,edit: false,formData: {title: '',link: '',width: '',height: '',alt: '',sImg: ''}}},
- 在src-manage-store-mutations.js的第555行添加books的mutations初始化的内容,目前暂定books的数据库和ads一样,所以里面的内容先不修改,后期还是要改的:
12345678910111213141516171819202122232425[types.BOOKS_INFO_FORMSTATE](state, formState) {state.books.infoFormState.edit = formState.edit;state.books.infoFormState.formData = Object.assign({name: '',type: '1',height: '',comments: '',items: [],state: true,carousel: true}, formState.formData);},[types.BOOKS_ITEM_FORMSTATE](state, formState) {state.books.itemFormState.edit = formState.edit;state.books.itemFormState.show = formState.show;state.books.itemFormState.formData = Object.assign({title: '',link: '',width: '',height: '',alt: '',sImg: '',}, formState.formData);},
- 在src-manage-store-types.js的第31行添加Books的宏定义内容:
1234export const BOOKS_LIST = 'BOOKS_LIST';export const BOOKS_INFO_FORMSTATE = 'BOOKS_INFO_FORMSTATE';export const BOOKS_ITEM_FORMSTATE = 'BOOKS_ITEM_FORMSTATE';
- 在server-lib-controller-ads.js中复制ads.js,新建books.js的controller文件:并且修改里面所有的类名和函数名:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230const BaseComponent = require('../prototype/baseComponent');const BooksModel = require("../models").Ads;const BooksItemsModel = require("../models").AdsItems;const formidable = require('formidable');const { service, settings, validatorUtil, logUtil, siteFunc } = require('../../../utils');const shortid = require('shortid');const validator = require('validator')function checkFormData(req, res, fields) {let errMsg = '';if (fields._id && !siteFunc.checkCurrentId(fields._id)) {errMsg = '非法请求,请稍后重试!';}if (!validator.isLength(fields.name, 2, 15)) {errMsg = '2-15个非特殊字符!';}if (!validator.isLength(fields.comments, 5, 30)) {errMsg = '5-30个非特殊字符!';}if (errMsg) {res.send({state: 'error',type: 'ERROR_PARAMS',message: errMsg})}}class Books {constructor() {// super()}async getBooks(req, res, next) {try {let current = req.query.current || 1;let pageSize = req.query.pageSize || 10;let model = req.query.model; // 查询模式 full/simplelet queryObj = {};if (model === 'full') {pageSize = '1000'}const Ads = await BooksModel.find(queryObj).sort({ date: -1 }).skip(10 * (Number(current) - 1)).limit(Number(pageSize)).populate([{path: 'items'}]).exec();const totalItems = await BooksModel.count();res.send({state: 'success',docs: Ads,pageInfo: {totalItems,current: Number(current) || 1,pageSize: Number(pageSize) || 10}})} catch (err) {logUtil.error(err, req);res.send({state: 'error',type: 'ERROR_DATA',message: '获取Ads失败' + err})}}async getOneBook(req, res, next) {try {let targetId = req.query.id;let state = req.query.state, queryObj = { _id: targetId };if (state) queryObj.state = stateconst ad = await BooksModel.findOne(queryObj).populate([{path: 'items'}]).exec();res.send({state: 'success',doc: ad || {}})} catch (error) {logUtil.error(err, req);res.send({state: 'error',type: 'ERROR_DATA',message: '获取Ad失败' + err})}}async addBooks(req, res, next) {const form = new formidable.IncomingForm();form.parse(req, async (err, fields, files) => {try {checkFormData(req, res, fields);} catch (err) {console.log(err.message, err);res.send({state: 'error',type: 'ERROR_PARAMS',message: err.message})return}const adObj = {name: fields.name,state: fields.state,height: fields.height,carousel: fields.carousel,type: fields.type,comments: fields.comments}let itemIdArr = [], adsItems = fields.items;if (adsItems.length > 0) {for (let i = 0; i < adsItems.length; i++) {const newAdItem = new BooksItemsModel(adsItems[i]);let newItem = await newAdItem.save();itemIdArr.push(newItem._id);}}adObj.items = itemIdArr;const newAds = new BooksModel(adObj);try {await newAds.save();res.send({state: 'success',id: newAds._id});} catch (err) {logUtil.error(err, req);res.send({state: 'error',type: 'ERROR_IN_SAVE_DATA',message: '保存数据失败:',})}})}async updateBooks(req, res, next) {const form = new formidable.IncomingForm();form.parse(req, async (err, fields, files) => {try {checkFormData(req, res, fields);} catch (err) {console.log(err.message, err);res.send({state: 'error',type: 'ERROR_PARAMS',message: err.message})return}const userObj = {name: fields.name,state: fields.state,height: fields.height,carousel: fields.carousel,type: fields.type,comments: fields.comments}const item_id = fields._id;let itemIdArr = [], adsItems = fields.items;try {if (adsItems.length > 0) {for (let i = 0; i < adsItems.length; i++) {let targetItem = adsItems[i], currentId = '';if (targetItem._id) {currentId = targetItem._id;await BooksItemsModel.findOneAndUpdate({ _id: targetItem._id }, { $set: targetItem });} else {const newAdItem = new BooksItemsModel(targetItem);let newItem = await newAdItem.save();currentId = newItem._id;}itemIdArr.push(currentId);}}userObj.items = itemIdArr;await BooksModel.findOneAndUpdate({ _id: item_id }, { $set: userObj });res.send({state: 'success'});} catch (err) {logUtil.error(err, req);res.send({state: 'error',type: 'ERROR_IN_SAVE_DATA',message: '更新数据失败:' + err,})}})}async delBooks(req, res, next) {try {let errMsg = '', targetIds = req.query.ids;if (!siteFunc.checkCurrentId(targetIds)) {errMsg = '非法请求,请稍后重试!';} else {targetIds = targetIds.split(',');}if (errMsg) {res.send({state: 'error',message: errMsg,})}for (let i = 0; i < targetIds.length; i++) {let currentId = targetIds[i];let targetAd = await BooksModel.findOne({ _id: currentId });await BooksItemsModel.remove({ '_id': { $in: targetAd.items } });await BooksModel.remove({ _id: currentId });}res.send({state: 'success'});} catch (err) {logUtil.error(err, req);res.send({state: 'error',type: 'ERROR_IN_SAVE_DATA',message: '删除数据失败:' + err,})}}}module.exports = new Books();
- 在server-lib-controller-models文件中复制Ads.js和AdsItems.js文件,修改里面的文件名,并且定义对应的数据库。
书籍单元表:
1234567891011121314151617181920212223242526272829/*** Created by Administrator on 2015/4/15.* 书籍管理,书籍单元*/var mongoose = require('mongoose');var shortid = require('shortid');var Schema = mongoose.Schema;var BooksItemsSchema = new Schema({_id: {type: String,'default': shortid.generate},title: String,link: String, // 广告链接width: Number,height: { type: Number, default: 1 },target: { type: String, default: '_blank' },sImg: String, // 图片路径date: { type: Date, default: Date.now },alt: String // 广告alt标识});var BooksItems = mongoose.model("BooksItems", BooksItemsSchema);module.exports = BooksItems;书籍表:
1234567891011121314151617181920212223242526272829303132333435363738/*** Created by Administrator on 2017/4/15.* 广告管理*/var mongoose = require('mongoose');var shortid = require('shortid');var Schema = mongoose.Schema;var moment = require('moment')var BooksItems = require('./BooksItems');var BooksSchema = new Schema({_id: {type: String,'default': shortid.generate},name: String,type: { type: String, default: "0" }, // 展示形式 0文字 1图片 2友情链接carousel: { type: Boolean, default: true }, // 针对图片是否轮播state: { type: Boolean, default: true }, // 广告状态,是否显示height: { type: Number, default: 50 },date: { type: Date, default: Date.now },items: [{ type: String, ref: 'BooksItems' }], // 广告列表idcomments: String, // 描述});BooksSchema.set('toJSON', { getters: true, virtuals: true });BooksSchema.set('toObject', { getters: true, virtuals: true });BooksSchema.path('date').get(function (v) {return moment(v).format("YYYY-MM-DD HH:mm:ss");});var Books = mongoose.model("Books", BooksSchema);module.exports = Books; - 修改server-lib-controller-books.js的第二三行的代码:
123const BooksModel = require("../models").Books;const BooksItemsModel = require("../models").BooksItems;
- 修改src-store-services.js的第229行代码:
1234567891011121314151617181920getBooksList(params) {return reqJsonData('manage/books/getList', params, 'get')},getOneBook(params) {return reqJsonData('manage/books/getOne', params, 'get')},addOneBook(params) {return reqJsonData('manage/books/addOne', params)},updateBooks(params) {return reqJsonData('manage/books/updateOne', params)},delBooks(params) {return reqJsonData('manage/books/delete', params, 'get')}
- 修改src-store-actions的390行,增加对应的内容:
1234567891011121314151617181920212223242526272829303132333435getBooksList({commit}, params = {}) {services.getBooksList(params).then((result) => {commit(types.BOOKS_LIST, result.data)})},booksInfoForm: ({commit}, params = {}) => {commit(types.BOOKS_INFO_FORMSTATE, {edit: params.edit,formData: params.formData})},showBooksItemForm: ({commit}, params = {edit: false,formData: {}}) => {commit(types.BOOKS_ITEM_FORMSTATE, {show: true,edit: params.edit,formData: params.formData})},hideBooksItemForm: ({commit}) => {commit(types.BOOKS_ITEM_FORMSTATE, {show: false})},
- 修改src-manage-books-index.vue的代码为:
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455<template><div class="adminUser"><el-row class="dr-datatable"><el-col :span="24"><TopBar type="books"></TopBar><DataTable :dataList="booksList.docs"></DataTable><Pagination :pageInfo="booksList.pageInfo" pageType="books"></Pagination></el-col></el-row></div></template><script>import InfoForm from './infoForm'import DataTable from './dataTable.vue';import TopBar from '../common/TopBar.vue';import Pagination from '../common/Pagination.vue';import {mapGetters,mapActions} from 'vuex'export default {name: 'index',data() {return {}},components: {DataTable,TopBar,InfoForm,Pagination},methods: mapActions([]),computed: {...mapGetters(['booksList']),formState() {return this.$store.getters.booksInfoForm}},mounted() {this.$store.dispatch('getBooksList');}}</script><style lang=""></style>
- 修改server-routers-managers.js的第221行添加对应的路由:
123456789101112131415161718/*** 书籍管理*/router.get('/books/getList', authToken, authPower, Books.getBooks);// 获取单个广告router.get('/books/getOne', authToken, authPower, Books.getOneBook);// 新增广告router.post('/books/addOne', authToken, authPower, Books.addBooks);// 更新单个广告router.post('/books/updateOne', authToken, authPower, Books.updateBooks);// 删除广告router.get('/books/delete', authToken, authPower, Books.delBooks);
并且在第19行引入Books的控制器:
123456789101112131415161718const {AdminUser,AdminGroup,AdminResource,ContentCategory,Content,ContentTag,User,Message,SystemConfig,DataOptionLog,SystemOptionLog,UserNotify,Notify,Ads,Books} = require('../lib/controller'); - server-lib-controller-index.js中15行加入Books类的导出,这是报错的原因:
12exports.Books = require('./books');
- server-lib-models-index.js中第44行中加入导出数据库的两句:
123exports.Books = require('./Books');exports.BooksItems = require('./BooksItems');