first commit

This commit is contained in:
编码猿
2024-09-27 02:06:13 +08:00
commit 852d94fbb9
36760 changed files with 3274413 additions and 0 deletions

View File

@@ -0,0 +1,73 @@
/*
Navicat Premium Data Transfer
Source Server : 本地数据库
Source Server Type : MySQL
Source Server Version : 80013
Source Host : localhost:3306
Source Schema : Novel
Target Server Type : MySQL
Target Server Version : 80013
File Encoding : 65001
Date: 20/01/2019 23:47:49
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for novel_collection
-- ----------------------------
DROP TABLE IF EXISTS `novel_collection`;
CREATE TABLE `novel_collection` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`collection_user` varchar(255) NOT NULL COMMENT '用户的id',
`collection_bookid` varchar(255) DEFAULT NULL COMMENT '用户收藏的小说id',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of novel_collection
-- ----------------------------
BEGIN;
INSERT INTO `novel_collection` VALUES (1, '1', '25/25991/');
INSERT INTO `novel_collection` VALUES (2, '1', '29/29000/');
INSERT INTO `novel_collection` VALUES (3, '1', '27/27613/');
INSERT INTO `novel_collection` VALUES (4, '1', '25/25952/');
INSERT INTO `novel_collection` VALUES (5, '1', '26/26966/');
INSERT INTO `novel_collection` VALUES (6, '1', '25/25155/');
INSERT INTO `novel_collection` VALUES (7, '1', '26/26472/');
INSERT INTO `novel_collection` VALUES (8, '2', '27/27613/');
COMMIT;
-- ----------------------------
-- Table structure for novel_user
-- ----------------------------
DROP TABLE IF EXISTS `novel_user`;
CREATE TABLE `novel_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_phone` varchar(11) DEFAULT NULL,
`user_pwd` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`user_ip` varchar(15) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of novel_user
-- ----------------------------
BEGIN;
INSERT INTO `novel_user` VALUES (1, '15155145354', 'e10adc3949ba59abbe56e057f20f883e', '112.32.95.213');
INSERT INTO `novel_user` VALUES (2, '18305520337', 'e10adc3949ba59abbe56e057f20f883e', '112.32.95.213');
INSERT INTO `novel_user` VALUES (3, '18305520334', 'e10adc3949ba59abbe56e057f20f883e', '112.32.95.213');
INSERT INTO `novel_user` VALUES (4, '15155145352', '25f9e794323b453885f5181f1b624d0b', '112.32.95.213');
INSERT INTO `novel_user` VALUES (5, '18305520338', 'e10adc3949ba59abbe56e057f20f883e', '112.32.95.213');
INSERT INTO `novel_user` VALUES (6, '18305520339', 'e10adc3949ba59abbe56e057f20f883e', '112.32.95.213');
INSERT INTO `novel_user` VALUES (7, '15155145350', 'e10adc3949ba59abbe56e057f20f883e', '112.32.95.213');
INSERT INTO `novel_user` VALUES (8, '13003085278', 'e10adc3949ba59abbe56e057f20f883e', '112.32.95.213');
INSERT INTO `novel_user` VALUES (9, '18305520336', 'e10adc3949ba59abbe56e057f20f883e', '112.32.95.213');
INSERT INTO `novel_user` VALUES (10, '15155145359', 'e10adc3949ba59abbe56e057f20f883e', '112.32.95.213');
COMMIT;
SET FOREIGN_KEY_CHECKS = 1;

Binary file not shown.

After

Width:  |  Height:  |  Size: 357 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 307 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 618 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 874 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 475 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 169 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

View File

@@ -0,0 +1,12 @@
const express = require('express')
const router = express.Router()
const http = require('./http')
const utils = require('./utils')
const config = require('./config')
const mysql = require('yn-mysql-utils')
const md5 = require('md5')
let db = new mysql(config.mysql)
module.exports = { express , router, http , utils, config, db, md5}

View File

@@ -0,0 +1,73 @@
var createError = require('http-errors');
var express = require('express');
var loadRouter = require('express-load-router');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var config = require('./config');
var session = require('express-session')
var app = express();
var classRouter = require('./controller/class');
var IndexRouter = require('./controller/index');
var InfoRouter = require('./controller/info');
var likeActionRouter = require('./controller/user/likeAction');
var loginActionRouter = require('./controller/user/loginAction');
// 后端允许前端跨域
app.all('*', (req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
// 使用 session 中间件
app.use(session({
secret : 'secret', // 对session id 相关的cookie 进行签名
resave : false,
saveUninitialized: true, // 是否保存未初始化的会话
cookie : {
maxAge : 1000 * 60 * 10, // 设置 session 的有效时间,单位毫秒
},
}));
app.use(`${config.ApiBaseUrl}`, classRouter)
app.use(`${config.ApiBaseUrl}`, IndexRouter)
app.use(`${config.ApiBaseUrl}`, InfoRouter)
app.use(`${config.ApiBaseUrl}`, loginActionRouter)
app.use(`${config.ApiBaseUrl}`, likeActionRouter)
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.json({
status: 404,
message: err.message
})
});
module.exports = app;

View File

@@ -0,0 +1,87 @@
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('xiaoshuo-backend:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
console.log("后端api接口运行在http://127.0.0.1:3000/")
}

View File

@@ -0,0 +1,66 @@
module.exports = {
ApiBaseUrl: '/api/json/1.0/',
getIpAddres: 'http://2019.ip138.com/ic.asp',
mysql: {
host : '127.0.0.1',
user : 'root',
password : 'lb714500',
database : 'Novel',
connectionLimit : 10
},
TargetUrl: {
baseUrl: 'http://www.xbiquge.la/',
class: {
title: 'fenlei/',
fantasy: {
id: '1_',
url: 'xuanhuanxiaoshuo/'
},
though: {
id: '2_',
url: 'xiuzhenxiaoshuo/'
},
urban: {
id: '3_',
url: 'dushixiaoshuo/'
},
passThrough: {
id: '4_',
url: 'chuanyuexiaoshuo/'
},
game: {
id: '5_',
url: 'wangyouxiaoshuo/'
},
scienceFiction: {
id: '6_',
url: 'kehuanxiaoshuo/'
},
hotlist: {
url: 'paihangbang/'
}
}
},
sql: {
index: {
selectData: 'SELECT * FROM novel_book WHERE book_key = ? AND book_page = ?',
selectSave: 'SELECT * FROM novel_book WHERE book_key = ? AND book_page = ? AND book_hot = ?',
inrset: 'INSERT INTO novel_book(book_title,book_introduce,book_img,book_author,book_time,book_url,book_hot,book_page,book_key) VALUES (?,?,?,?,?,?,?,?,?)',
delete: 'DELETE FROM novel_book WHERE book_key = ? AND book_hot = 1'
},
user: {
getUserInfo: 'SELECT * FROM novel_user WHERE id = ?',
checkUser: 'SELECT * FROM novel_user WHERE user_phone = ?',
login: 'SELECT id,user_phone,user_ip FROM novel_user WHERE user_phone = ? AND user_pwd = ?',
userReg: 'INSERT INTO novel_user(user_phone,user_pwd,user_ip) VALUES (?,?,?)',
checkBook: 'SELECT * FROM novel_collection WHERE collection_user = ? AND collection_bookid = ?',
insertBook: 'INSERT INTO novel_collection(collection_user,collection_bookid) VALUES (?,?)',
selectBook: 'SELECT * FROM novel_collection WHERE collection_user = ?',
deleteBook: 'DELETE FROM novel_collection WHERE collection_user = ? AND collection_bookid = ?'
}
},
apiStatus: {
status: 200,
data: null
}
}

View File

@@ -0,0 +1,70 @@
const { http, utils, db, config,router } = require("../../_");
// http://127.0.0.1:3000/api/json/1.0/class?class=1&page=1
router.get('/class', async function(req,res,next){
// 请求数据 and 返回dom数据
let $ = await utils.AnalyticalData({ class:req.query.class, page: req.query.page } ),
left = [],
father = null;
/**
* 存在 action 爬取每个分类下面的更多小说
*/
if(req.query.hasOwnProperty("action")){
// http://127.0.0.1:3000/api/json/1.0/class?class=2&page=1&action=more
father = $("#newscontent .l ul li")
father.each(function(){
left.push({
title: $(this).find(".s2 a").text(),
url: $(this).find(".s2 a").attr("href")
})
})
let newList = []
left.forEach(async (item) => {
let $ = await utils.AnalyticalData({ siteUrl: item.url } )
newList.push({
title: $('#maininfo #info').find('h1').text(),
imgURL: $('#sidebar #fmimg').find('img').attr('src'),
introduce: $('#maininfo #intro').children().last().text(),
author: ($('#maininfo #info').find('h1+p').text()).substring(7),
url: item.url
})
if(newList.length == 30) {
return res.json(newList)
}
})
/**
* 不存在 action 爬取每个分类小面的推荐小说
*/
} else {
// http://127.0.0.1:3000/api/json/1.0/class?class=2
father = $("#hotcontent .ll .item")
father.each(async function() {
left.push({
title: $(this).find("dl dt a").text(),
imgURL: $(this).find(".image img").attr("src"),
author: $(this).find("dl dt span").text(),
introduce: $(this).find("dl dd").text(),
url: $(this).find(".image a").attr("href")
})
})
return res.json(left)
}
})
module.exports = router

View File

@@ -0,0 +1,8 @@
const { http, utils, db, config,router } = require("../../_");
router.get('/index', async function(req, res, next) {
console.log('index');
})
module.exports = router

View File

@@ -0,0 +1,66 @@
const { http, utils, db, config,router } = require("../../_");
/**
* 小说详情页面
* 地址http://127.0.0.1:3000/api/json/1.0/info?id=28/28039/
*/
router.get('/info', async (req, res, next) => {
let id = req.query.id,
action = req.query.action == undefined ? null: req.query.action,
InfoData = {};
try {
let $ = utils.returnDOM(await http.get({ url: `${config.TargetUrl.baseUrl}${id}` }));
InfoData.title = $("#info").find("h1").text()
InfoData.author = $("#info p").eq(0).text()
InfoData.updateTime = $("#info p").eq(2).text()
InfoData.imgUrl = $("#fmimg img").attr("src")
InfoData.introduce = $("#intro p").eq(1).text()
InfoData.oldChapter = []
let father = $("#list dl dd a");
father.each(function (item) {
InfoData.oldChapter.push({
chapterTitle: $(this).text(),
chapterUrl: $(this).attr("href"),
})
})
if(action == null) {
InfoData.newChapter = {}
InfoData.newChapter.newTitle = $("#info p").eq(3).find("a").text()
InfoData.newChapter.newUrl = $("#info p").eq(3).find("a").attr("href")
utils.returnJson(200,InfoData,res)
} else {
res.json(InfoData)
}
}catch (e) {
console.log(e)
}
})
/**
* 阅读小说接口
* 地址http://127.0.0.1:3000/api/json/1.0/read?id=/28/28039/13633573.html
*/
router.get('/read', async (req, res, next) => {
let id = req.query.id;
try {
let $ = utils.returnDOM(await http.get({ url: `${config.TargetUrl.baseUrl}${id}` }));
utils.returnJson(200,{
title: $(".bookname h1").text(),
content: (unescape($("#content").html().replace(/&#x/g,'%u').replace(/;/g,''))).replace(/%uA0%uA0%uA0%uA0|\n/gi,'  ')
},res)
}catch (e) {
console.log(e)
}
})
module.exports = router

View File

@@ -0,0 +1,83 @@
const { http, utils, db, config,router,md5 } = require("../../_");
/**
* 检查用户是否已经添加过某本小说
*/
router.post('/user/checkbook', async function (req, res, next) {
let userid = req.body.userid,
bookid = req.body.bookid;
let Check = await db.Query({ sql: config.sql.user.checkBook, par: [ userid, bookid ] });
if(Check.length) {
utils.returnJson(200,"已收藏",res);
}else {
utils.returnJson(200,"未收藏",res);
}
});
/**
* 用户添加小说到书架
*/
router.post('/user/addbok', async function (req, res, next) {
let userid = req.body.userid,
bookid = req.body.bookid;
let add = await db.Query({ sql: config.sql.user.insertBook, par: [ userid, bookid ] });
if(add.message.length == 0) {
utils.returnJson(200,"添加成功",res);
}else {
utils.returnJson(404,"添加失败",res);
}
})
/**
* 获取用户书架中收藏的书
* http://127.0.0.1:3000/api/json/1.0/user/getbook?userid=1
*/
router.get('/user/getbook', async function (req, res, next) {
let userid = req.query.userid;
let getBook = await db.Query({ sql: config.sql.user.selectBook, par: [ userid ] }),
infoData = [],
keys = 0;
if(getBook.length ==0) {
utils.returnJson(404,"数据没有数据",res);
}else {
getBook.forEach(async (value , index) => {
infoData.push(await http.get({ url: `http://127.0.0.1:3000/api/json/1.0/info?action=back&id=${value.collection_bookid}` }));
infoData[keys].bookid = value.collection_bookid
keys++;
if(keys == getBook.length) {
utils.returnJson(200,infoData,res);
}
})
}
})
/**
* 获取用户书架中收藏的书
* http://127.0.0.1:3000/api/json/1.0/user/deletebook?uid=1&bid=26/26966/
*/
router.get('/user/deletebook', async function (req, res, next) {
let userid = req.query.uid,
bookid = req.query.bid;
let delbook = await db.Query({ sql: config.sql.user.deleteBook, par: [ userid, bookid ] });
if(delbook.message.length == 0) {
utils.returnJson(200,"删除成功",res);
}else {
utils.returnJson(404,"删除失败",res);
}
})
module.exports = router

View File

@@ -0,0 +1,65 @@
const { http, utils, db, config,router,md5 } = require("../../_");
/**
* 用户登录
*/
router.post('/user/login', async function (req, res, next) {
let UserName = req.body.name,
UserPwd = req.body.pwd,
IP = req.body.ip;
let UserInfo = await db.Query({ sql: config.sql.user.login, par: [ UserName, md5(UserPwd) ] });
if(UserInfo.length) {
req.session.userinfo = UserInfo;
utils.returnJson(200,UserInfo[0],res);
}else {
utils.returnJson(404,'账号和密码不匹配',res)
}
});
/**
* 注册账户
*/
router.post('/user/reg', async (req, res, next) => {
let userName = req.body.name,
UserPwd = req.body.pwd;
if(/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(userName)) {
if( (await db.Query({ sql: config.sql.user.checkUser, par: [userName] })).length ) {
utils.returnJson(404,'手机号已存在',res)
}else {
let userReg = await db.Query({ sql: config.sql.user.userReg, par: [userName, md5(UserPwd), await utils.GetIp()] })
req.session.userinfo = await db.Query({ sql: config.sql.user.getUserInfo, par: [userReg.insertId] })
utils.returnJson(200,'regSuccess',res)
}
}else {
utils.returnJson(404,'手机号格式不正确',res)
}
});
/**
* 退出登录
*/
router.post('/user/outLogin', async (req, res, next) => {
});
/**
* 检查用户是否登录 前端检查 + 后端session检查
*/
router.get('/user/checkLogin', async (req, res, next) => {
console.log(req.session.userinfo)
// if(req.session.userinfo.length) {
// utils.returnJson(200,'Logined',res)
// }else {
// utils.returnJson(404,'noLogin',res)
// }
});
/**
* 重置密码
*/
router.post('/user/restPwd', async (req, res, next) => {
});
module.exports = router

View File

@@ -0,0 +1,15 @@
# POST http://127.0.0.1:3000/api/json/1.0/user/reg HTTP/1.1
# content-type: application/json
# {
# "name": "15155145354",
# "pwd": "123456"
# }
POST http://127.0.0.1:3000/api/json/1.0/user/login HTTP/1.1
content-type: application/json
{
"name": "15155145354",
"pwd": "123456"
}

View File

@@ -0,0 +1,19 @@
const axios = require('axios');
const config = require('./../config');
// 配置爬虫的基地址
axios.defaults.baseURL = config.TargetUrl.baseUrl;
module.exports = {
get(params) {
return new Promise(function(resolve,reject){
axios.get(params.url)
.then( (success) => {
resolve(success.data);
})
.catch( (error) => {
reject(error);
});
})
}
}

View File

@@ -0,0 +1,21 @@
{
"name": "xiaoshuo-backend",
"version": "1.2.1",
"private": true,
"scripts": {
"dev": "node-dev ./bin/www"
},
"dependencies": {
"md5": "^2.2.1",
"axios": "^0.18.0",
"cheerio": "^1.0.0-rc.2",
"cookie-parser": "~1.4.3",
"debug": "~2.6.9",
"express": "~4.16.0",
"express-load-router": "^2.1.4",
"express-session": "^1.15.6",
"http-errors": "~1.6.2",
"morgan": "~1.9.0",
"yn-mysql-utils": "^1.0.4"
}
}

View File

@@ -0,0 +1,38 @@
const config = require('../config')
const http = require('../http')
const cheerio = require('cheerio')
module.exports = {
async AnalyticalData(par) {
let urls = '';
if(par.hasOwnProperty('page')) {
urls = `${config.TargetUrl.class.title}${par.class}_${par.page}.html`
} else if(par.hasOwnProperty('siteUrl')){
urls = par.siteUrl
} else {
urls = config.TargetUrl.class.hotlist
}
// 网络请求获取 目标 页面的 html源码
return this.returnDOM(await http.get({ url: urls }))
},
returnDOM(data) {
return cheerio.load(data)
},
returnJson(status, data,res) {
config.apiStatus.status = status
config.apiStatus.data = data
res.json(config.apiStatus);
},
/**
* 返回客户端ip地址
* @returns {Promise<*|string>}
* @constructor
*/
async GetIp () {
let ipData = await http.get({ url: config.getIpAddres })
return ipData.match(/\[([\s\S]*?)\]/)[1]
}
}

View File

@@ -0,0 +1,54 @@
const { http, utils, db, config,router } = require("../../_");
// http://127.0.0.1:3000/api/json/1.0/class?class=1&page=1
router.get('/class', async function(req,res,next){
// 请求数据 and 返回dom数据
let $ = await utils.AnalyticalData({ class:req.query.class, page: req.query.page } ),
left = [],
father = null;
/**
* 存在 action 爬取每个分类下面的更多小说
*/
if(req.query.hasOwnProperty("action")){
// http://127.0.0.1:3000/api/json/1.0/class?class=2&page=1&action=more
father = $("#newscontent .l ul li")
father.each(function(){
left.push({
title: $(this).find(".s2 a").text(),
url: $(this).find(".s2 a").attr("href")
})
})
/**
* 不存在 action 爬取每个分类小面的推荐小说
*/
} else {
// http://127.0.0.1:3000/api/json/1.0/class?class=2
father = $("#hotcontent .ll .item")
// 插入数据之前先删除之前的数据
// await db.Query({ sql: config.sql.index.delete, par: [ req.query.class ] });
father.each(async function() {
left.push({
title: $(this).find("dl dt a").text(),
imgURL: $(this).find(".image img").attr("src"),
author: $(this).find("dl dt span").text(),
introduce: $(this).find("dl dd").text(),
url: $(this).find(".image a").attr("href")
})
})
}
return res.json(left)
})
module.exports = router

View File

@@ -0,0 +1,18 @@
{
"presets": [
["env", {
"modules": false,
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}],
"stage-2"
],
"plugins": ["transform-vue-jsx", "transform-runtime"],
"env": {
"test": {
"presets": ["env", "stage-2"],
"plugins": ["transform-vue-jsx", "transform-es2015-modules-commonjs", "dynamic-import-node"]
}
}
}

View File

@@ -0,0 +1,9 @@
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

View File

@@ -0,0 +1,5 @@
/build/
/config/
/dist/
/*.js
/test/unit/coverage/

View File

@@ -0,0 +1,29 @@
// https://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parserOptions: {
parser: 'babel-eslint'
},
env: {
browser: true,
},
extends: [
// https://github.com/vuejs/eslint-plugin-vue#priority-a-essential-error-prevention
// consider switching to `plugin:vue/strongly-recommended` or `plugin:vue/recommended` for stricter rules.
'plugin:vue/essential',
// https://github.com/standard/standard/blob/master/docs/RULES-en.md
'standard'
],
// required to lint *.vue files
plugins: [
'vue'
],
// add your custom rules here
rules: {
// allow async-await
'generator-star-spacing': 'off',
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
}
}

View File

@@ -0,0 +1,15 @@
.DS_Store
node_modules/
/dist/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
/test/unit/coverage/
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln

View File

@@ -0,0 +1,10 @@
// https://github.com/michael-ciniawsky/postcss-load-config
module.exports = {
"plugins": {
"postcss-import": {},
"postcss-url": {},
// to edit target browsers: use "browserslist" field in package.json
"autoprefixer": {}
}
}

View File

@@ -0,0 +1,27 @@
# xiaoshuo-fontend
> A Vue.js project
## Build Setup
``` bash
# install dependencies
npm install
# serve with hot reload at localhost:8080
npm run dev
# build for production with minification
npm run build
# build for production and view the bundle analyzer report
npm run build --report
# run unit tests
npm run unit
# run all tests
npm test
```
For a detailed explanation on how things work, check out the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader).

View File

@@ -0,0 +1,41 @@
'use strict'
require('./check-versions')()
process.env.NODE_ENV = 'production'
const ora = require('ora')
const rm = require('rimraf')
const path = require('path')
const chalk = require('chalk')
const webpack = require('webpack')
const config = require('../config')
const webpackConfig = require('./webpack.prod.conf')
const spinner = ora('building for production...')
spinner.start()
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
if (err) throw err
webpack(webpackConfig, (err, stats) => {
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build.
chunks: false,
chunkModules: false
}) + '\n\n')
if (stats.hasErrors()) {
console.log(chalk.red(' Build failed with errors.\n'))
process.exit(1)
}
console.log(chalk.cyan(' Build complete.\n'))
console.log(chalk.yellow(
' Tip: built files are meant to be served over an HTTP server.\n' +
' Opening index.html over file:// won\'t work.\n'
))
})
})

View File

@@ -0,0 +1,54 @@
'use strict'
const chalk = require('chalk')
const semver = require('semver')
const packageConfig = require('../package.json')
const shell = require('shelljs')
function exec (cmd) {
return require('child_process').execSync(cmd).toString().trim()
}
const versionRequirements = [
{
name: 'node',
currentVersion: semver.clean(process.version),
versionRequirement: packageConfig.engines.node
}
]
if (shell.which('npm')) {
versionRequirements.push({
name: 'npm',
currentVersion: exec('npm --version'),
versionRequirement: packageConfig.engines.npm
})
}
module.exports = function () {
const warnings = []
for (let i = 0; i < versionRequirements.length; i++) {
const mod = versionRequirements[i]
if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
warnings.push(mod.name + ': ' +
chalk.red(mod.currentVersion) + ' should be ' +
chalk.green(mod.versionRequirement)
)
}
}
if (warnings.length) {
console.log('')
console.log(chalk.yellow('To use this template, you must update following to modules:'))
console.log()
for (let i = 0; i < warnings.length; i++) {
const warning = warnings[i]
console.log(' ' + warning)
}
console.log()
process.exit(1)
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

View File

@@ -0,0 +1,101 @@
'use strict'
const path = require('path')
const config = require('../config')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const packageConfig = require('../package.json')
exports.assetsPath = function (_path) {
const assetsSubDirectory = process.env.NODE_ENV === 'production'
? config.build.assetsSubDirectory
: config.dev.assetsSubDirectory
return path.posix.join(assetsSubDirectory, _path)
}
exports.cssLoaders = function (options) {
options = options || {}
const cssLoader = {
loader: 'css-loader',
options: {
sourceMap: options.sourceMap
}
}
const postcssLoader = {
loader: 'postcss-loader',
options: {
sourceMap: options.sourceMap
}
}
// generate loader string to be used with extract text plugin
function generateLoaders (loader, loaderOptions) {
const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader]
if (loader) {
loaders.push({
loader: loader + '-loader',
options: Object.assign({}, loaderOptions, {
sourceMap: options.sourceMap
})
})
}
// Extract CSS when that option is specified
// (which is the case during production build)
if (options.extract) {
return ExtractTextPlugin.extract({
use: loaders,
fallback: 'vue-style-loader'
})
} else {
return ['vue-style-loader'].concat(loaders)
}
}
// https://vue-loader.vuejs.org/en/configurations/extract-css.html
return {
css: generateLoaders(),
postcss: generateLoaders(),
less: generateLoaders('less'),
sass: generateLoaders('sass', { indentedSyntax: true }),
scss: generateLoaders('sass'),
stylus: generateLoaders('stylus'),
styl: generateLoaders('stylus')
}
}
// Generate loaders for standalone style files (outside of .vue)
exports.styleLoaders = function (options) {
const output = []
const loaders = exports.cssLoaders(options)
for (const extension in loaders) {
const loader = loaders[extension]
output.push({
test: new RegExp('\\.' + extension + '$'),
use: loader
})
}
return output
}
exports.createNotifierCallback = () => {
const notifier = require('node-notifier')
return (severity, errors) => {
if (severity !== 'error') return
const error = errors[0]
const filename = error.file && error.file.split('!').pop()
notifier.notify({
title: packageConfig.name,
message: severity + ': ' + error.name,
subtitle: filename || '',
icon: path.join(__dirname, 'logo.png')
})
}
}

View File

@@ -0,0 +1,22 @@
'use strict'
const utils = require('./utils')
const config = require('../config')
const isProduction = process.env.NODE_ENV === 'production'
const sourceMapEnabled = isProduction
? config.build.productionSourceMap
: config.dev.cssSourceMap
module.exports = {
loaders: utils.cssLoaders({
sourceMap: sourceMapEnabled,
extract: isProduction
}),
cssSourceMap: sourceMapEnabled,
cacheBusting: config.dev.cacheBusting,
transformToRequire: {
video: ['src', 'poster'],
source: 'src',
img: 'src',
image: 'xlink:href'
}
}

View File

@@ -0,0 +1,100 @@
'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
const createLintingRule = () => ({
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter'),
emitWarning: !config.dev.showEslintErrorsInOverlay
}
})
module.exports = {
context: path.resolve(__dirname, '../'),
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json', '.less'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'~': resolve('src'),
}
},
module: {
rules: [
...(config.dev.useEslint ? [createLintingRule()] : []),
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.less$/,
loader: "style-loader!css-loader!less-loader",
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
},
{
test : /\.jade$/,
loader : 'jade-loader'
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('media/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
},
node: {
// prevent webpack from injecting useless setImmediate polyfill because Vue
// source contains it (although only uses it if it's native).
setImmediate: false,
// prevent webpack from injecting mocks to Node native modules
// that does not make sense for the client
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty'
}
}

View File

@@ -0,0 +1,95 @@
'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')
const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)
const devWebpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
},
// cheap-module-eval-source-map is faster for development
devtool: config.dev.devtool,
// these devServer options should be customized in /config/index.js
devServer: {
clientLogLevel: 'warning',
historyApiFallback: {
rewrites: [
{ from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
],
},
hot: true,
contentBase: false, // since we use CopyWebpackPlugin.
compress: true,
host: HOST || config.dev.host,
port: PORT || config.dev.port,
open: config.dev.autoOpenBrowser,
overlay: config.dev.errorOverlay
? { warnings: false, errors: true }
: false,
publicPath: config.dev.assetsPublicPath,
proxy: config.dev.proxyTable,
quiet: true, // necessary for FriendlyErrorsPlugin
watchOptions: {
poll: config.dev.poll,
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': require('../config/dev.env')
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.dev.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
module.exports = new Promise((resolve, reject) => {
portfinder.basePort = process.env.PORT || config.dev.port
portfinder.getPort((err, port) => {
if (err) {
reject(err)
} else {
// publish the new Port, necessary for e2e tests
process.env.PORT = port
// add port to devServer config
devWebpackConfig.devServer.port = port
// Add FriendlyErrorsPlugin
devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
compilationSuccessInfo: {
messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
},
onErrors: config.dev.notifyOnErrors
? utils.createNotifierCallback()
: undefined
}))
resolve(devWebpackConfig)
}
})
})

View File

@@ -0,0 +1,149 @@
'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const env = process.env.NODE_ENV === 'testing'
? require('../config/test.env')
: require('../config/prod.env')
const webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true,
usePostCSS: true
})
},
devtool: config.build.productionSourceMap ? config.build.devtool : false,
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
'process.env': env
}),
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
// extract css into its own file
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css'),
// Setting the following option to `false` will not extract CSS from codesplit chunks.
// Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
// It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`,
// increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
allChunks: true,
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSPlugin({
cssProcessorOptions: config.build.productionSourceMap
? { safe: true, map: { inline: false } }
: { safe: true }
}),
// generate dist index.html with correct asset hash for caching.
// you can customize output by editing /index.html
// see https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: process.env.NODE_ENV === 'testing'
? 'index.html'
: config.build.index,
template: 'index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: 'dependency'
}),
// keep module.id stable when vendor modules does not change
new webpack.HashedModuleIdsPlugin(),
// enable scope hoisting
new webpack.optimize.ModuleConcatenationPlugin(),
// split vendor js into its own file
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks (module) {
// any required modules inside node_modules are extracted to vendor
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, '../node_modules')
) === 0
)
}
}),
// extract webpack runtime and module manifest to its own file in order to
// prevent vendor hash from being updated whenever app bundle is updated
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
minChunks: Infinity
}),
// This instance extracts shared chunks from code splitted chunks and bundles them
// in a separate chunk, similar to the vendor chunk
// see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
new webpack.optimize.CommonsChunkPlugin({
name: 'app',
async: 'vendor-async',
children: true,
minChunks: 3
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
if (config.build.productionGzip) {
const CompressionWebpackPlugin = require('compression-webpack-plugin')
webpackConfig.plugins.push(
new CompressionWebpackPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
'\\.(' +
config.build.productionGzipExtensions.join('|') +
')$'
),
threshold: 10240,
minRatio: 0.8
})
)
}
if (config.build.bundleAnalyzerReport) {
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig

View File

@@ -0,0 +1,7 @@
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"'
})

View File

@@ -0,0 +1,76 @@
'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
// Use Eslint Loader?
// If true, your code will be linted during bundling and
// linting errors and warnings will be shown in the console.
useEslint: false,
// If true, eslint errors and warnings will also be shown in the error overlay
// in the browser.
showEslintErrorsInOverlay: false,
/**
* Source Maps
*/
// https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map',
// If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
cssSourceMap: true
},
build: {
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
/**
* Source Maps
*/
productionSourceMap: true,
// https://webpack.js.org/configuration/devtool/#production
devtool: '#source-map',
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
}
}

View File

@@ -0,0 +1,4 @@
'use strict'
module.exports = {
NODE_ENV: '"production"'
}

View File

@@ -0,0 +1,7 @@
'use strict'
const merge = require('webpack-merge')
const devEnv = require('./dev.env')
module.exports = merge(devEnv, {
NODE_ENV: '"testing"'
})

View File

@@ -0,0 +1,18 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>免费小说app</title>
<meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0" name="viewport"/>
<meta content="yes" name="apple-mobile-web-app-capable"/>
<meta content="black" name="apple-mobile-web-app-status-bar-style"/>
<meta content="telephone=no" name="format-detection"/>
<!-- 引入自适应类库不建议在main.js里引入 -->
<script src="http://unpkg.com/vue-ydui/dist/ydui.flexible.js"></script>
<link rel="stylesheet" href="http://at.alicdn.com/t/font_976730_nk6iqvvpus.css">
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>

View File

@@ -0,0 +1,90 @@
{
"name": "xiaoshuo-fontend",
"version": "1.0.0",
"description": "A Vue.js project",
"author": "bmy <2271608011@qq.com>",
"private": true,
"scripts": {
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
"start": "npm run dev",
"unit": "jest --config test/unit/jest.conf.js --coverage",
"test": "npm run unit",
"lint": "eslint --ext .js,.vue src test/unit",
"build": "node build/build.js"
},
"dependencies": {
"axios": "^0.18.0",
"less": "^3.9.0",
"less-loader": "^4.1.0",
"vue": "^2.5.2",
"vue-router": "^3.0.1",
"vue-ydui": "^1.2.5",
"vuex": "^3.0.1"
},
"devDependencies": {
"autoprefixer": "^7.1.2",
"babel-core": "^6.22.1",
"babel-eslint": "^8.2.1",
"babel-helper-vue-jsx-merge-props": "^2.0.3",
"babel-jest": "^21.0.2",
"babel-loader": "^7.1.1",
"babel-plugin-dynamic-import-node": "^1.2.0",
"babel-plugin-syntax-jsx": "^6.18.0",
"babel-plugin-transform-es2015-modules-commonjs": "^6.26.0",
"babel-plugin-transform-runtime": "^6.22.0",
"babel-plugin-transform-vue-jsx": "^3.5.0",
"babel-preset-env": "^1.3.2",
"babel-preset-stage-2": "^6.22.0",
"chalk": "^2.0.1",
"copy-webpack-plugin": "^4.0.1",
"css-loader": "^0.28.0",
"eslint": "^4.15.0",
"eslint-config-standard": "^10.2.1",
"eslint-friendly-formatter": "^3.0.0",
"eslint-loader": "^1.7.1",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-node": "^5.2.0",
"eslint-plugin-promise": "^3.4.0",
"eslint-plugin-standard": "^3.0.1",
"eslint-plugin-vue": "^4.0.0",
"extract-text-webpack-plugin": "^3.0.0",
"file-loader": "^1.1.4",
"friendly-errors-webpack-plugin": "^1.6.1",
"html-webpack-plugin": "^2.30.1",
"jade": "^1.11.0",
"jade-loader": "^0.8.0",
"jest": "^22.0.4",
"jest-serializer-vue": "^0.3.0",
"node-notifier": "^5.1.2",
"optimize-css-assets-webpack-plugin": "^3.2.0",
"ora": "^1.2.0",
"portfinder": "^1.0.13",
"postcss-import": "^11.0.0",
"postcss-loader": "^2.0.8",
"postcss-url": "^7.2.1",
"rimraf": "^2.6.0",
"semver": "^5.3.0",
"shelljs": "^0.7.6",
"uglifyjs-webpack-plugin": "^1.1.1",
"url-loader": "^0.5.8",
"vue-infinite-loading": "^2.4.3",
"vue-jest": "^1.0.2",
"vue-loader": "^13.3.0",
"vue-style-loader": "^3.0.1",
"vue-template-compiler": "^2.5.2",
"vuescroll": "^4.9.6",
"webpack": "^3.6.0",
"webpack-bundle-analyzer": "^2.9.0",
"webpack-dev-server": "^2.9.1",
"webpack-merge": "^4.1.0"
},
"engines": {
"node": ">= 6.0.0",
"npm": ">= 3.0.0"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
}

View File

@@ -0,0 +1,51 @@
<template lang="jade">
#app
v-navbar(v-if="this.hiddenNavbar")
div(:class="{content : this.isContent}")
router-view
v-tabbar(v-if="this.hiddenTabbar")
</template>
<script>
import { mapGetters } from "vuex";
import headComponents from './components/tpl/head'
import footerComponents from './components/tpl/footer'
export default {
name: 'App',
created() {
},
data () {
return {
}
},
methods: {
},
components: {
'v-navbar': headComponents,
'v-tabbar': footerComponents
},
computed: {
...mapGetters({
hiddenNavbar: 'HiddenNavbar',
hiddenTabbar: 'HiddenTabbar',
isContent: 'iscontent',
onscroll: 'onscroll'
})
},
}
</script>
<style lang="less">
@import './assets/less/_main';
.content {
padding: 1rem 0 0.8rem 0;
}
body {
background: #f4f4f4;
}
</style>

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -0,0 +1,51 @@
//-------------------- 重置UI框架样式 --------------------
.yd-navbar {
background: @global-color !important;
.yd-navbar-center-title {
color: @white-color !important;
}
.yd-navbar-item {
span {
color: @white-color !important;
}
}
}
// 修改轮播图小圆点的位置
.yd-slider-pagination {
justify-content: flex-end;
padding-right: 11px;
}
.yd-grids-4 .yd-grids-item:not(:nth-child(4n)):before {
width: 0;
}
.yd-navbar:after {
height: 0 !important;
}
.g-fix-ios-prevent-scroll {
position: inherit !important;
}
//-------------------- 连接被激活时候的颜色 --------------------
.router-link-active {
color: @global-color !important;
}
//-------------------- 去除隐藏滚动条的样式 --------------------
::-webkit-scrollbar {/*滚动条整体样式*/
width: 0px;
height: 0px;
}
::-webkit-scrollbar-thumb {/*滚动条里面小方块*/
border-radius: 0;
background: rgba(0, 0, 0, 0);
}
::-webkit-scrollbar-track {/*滚动条里面轨道*/
border-radius: 10px;
background: rgba(0, 0, 0, 0);
}

View File

@@ -0,0 +1,48 @@
font-face {
font-family: 'iconfont'; /* project id 976730 */
src: url('//at.alicdn.com/t/font_976730_nk6iqvvpus.eot');
src: url('//at.alicdn.com/t/font_976730_nk6iqvvpus.eot?#iefix') format('embedded-opentype'),
url('//at.alicdn.com/t/font_976730_nk6iqvvpus.woff') format('woff'),
url('//at.alicdn.com/t/font_976730_nk6iqvvpus.ttf') format('truetype'),
url('//at.alicdn.com/t/font_976730_nk6iqvvpus.svg#iconfont') format('svg');
}
[class^="icon-custom-"]:before, [class*=" icon-custom-"]:before {
font-family: 'iconfont';
}
.icon-custom-shuj:before {
content: '\e60a';
}
.icon-custom-shuc:before {
content: '\e73e';
}
.icon-custom-class:before {
content: '\e635';
}
.icon-custom-about:before {
content: '\e657';
}
.icon-custom-bangzhu:before {
content: '\e60e';
}
.icon-custom-qingchuhuancun:before {
content: '\e630';
}
.icon-custom-night:before {
content: '\e79d';
}
.icon-custom-setting:before {
content: '\e72a';
}
.icon-custom-banben:before {
content: '\e641';
}
.icon-custom-xieyi:before {
content: '\e658';
}
.icon-custom-start:before {
content: '\e63c';
}

View File

@@ -0,0 +1,11 @@
@import './_variables/index.less';
@import './_mixins/index.less';
@import './_icons/index.less';
@import './_cover/index.less';
// 首页的样式
@import './view/index/_main.less';
// 书架样式
@import './view/like/index.less';
// 详情页样式
@import './view/info/index.less';

View File

@@ -0,0 +1,12 @@
.rounded-corners (@radius: 10px) {
border-radius: @radius;
-webkit-border-radius: @radius;
-moz-border-radius: @radius;
}
.flex_layout (@dir: row, @content: space-between) {
display: flex;
flex-direction: @dir;
justify-content: @content;
align-items: center;
}

View File

@@ -0,0 +1,6 @@
@global-color: #a70a0a;
@white-color: #fff;
@BottomSecant: .2rem;

View File

@@ -0,0 +1 @@
@import "./index.less";

View File

@@ -0,0 +1,30 @@
.index {
.index-scroll {
width: 100%;
overflow-x: scroll;
background: @white-color;
position: fixed;
top: 1rem;
z-index: 9;
transform: translateZ(0);
ul {
width: 130%;
li {
float: left;
width: 1.9rem;
height: 0.8rem;
line-height: 0.8rem;
text-align: center;
a {
font-size: 17px;
}
}
}
}
.yd-grids-4 {
margin-bottom: @BottomSecant;
}
}
.yd-slider {
padding-top: 40px;
}

View File

@@ -0,0 +1,111 @@
@main-color: #f3f3f3;
@full-height: 100%;
.infos {
height: @full-height;
.info-background {
width: @full-height;
height: 4rem;
position: absolute;
top: 0;
z-index: 1;
filter: grayscale(50%) blur(30px);
}
.info-header {
width: @full-height;
height: 4rem;
position: absolute;
top: 0;
z-index: 2;
.flex_layout();
align-items: flex-end;
padding: 0 0.39rem 0.21rem 0.39rem;
.header-img {
img {
width: 1.81rem;
}
}
.header-info {
width: @full-height;
padding-left: 0.4rem;
align-self: center;
margin-top: 0.9rem;
p {
font-size: 0.36rem;
font-weight: 600;
letter-spacing: 0.02rem;
margin-bottom: 0.2rem;
color: @main-color;
}
.header-class {
margin-bottom: 0.16rem;
color: @main-color;
}
}
}
.info-introduce{
padding: 0.21rem 0.39rem;
color: #797879;
background: @white-color;
padding-top: 4.72rem;
.introduce-title {
font-size: 0.34rem;
margin-bottom: 0.2rem;
}
.introduce-content{
font-size: 0.28rem;
letter-spacing: 0.02rem;
}
.introduce-newbook {
.flex_layout(row,space-between);
margin-top: 0.48rem;
}
}
.info-booklist {
margin-top: 0.2rem;
padding-bottom: 1.2rem;
}
.info-read {
position: fixed;
width: 90%;
height: 1rem;
margin-left: -168.75px;
left: 50%;
text-align: center;
line-height: 1rem;
z-index: 9;
color: #fff;
bottom: 10px;
font-size: 0.36rem;
.add-base {
border-top-left-radius: 40px;
border-bottom-left-radius: 40px;
}
.add-bookshelf-active {
background: linear-gradient(to right, #FFC500, #FF9402);
}
.add-bookshelf-noactive {
background: linear-gradient(to right, #858485, #3c0a12);
}
.start-read {
background: linear-gradient(to right, #FF7A00, #FE560A);
border-top-right-radius: 40px;
border-bottom-right-radius: 40px;
}
}
}
.yd-back-icon:before, .yd-next-icon:before {
font-size: .48rem !important;
}
.yd-navbar {
width: 100%;
position: fixed;
top: 0;
z-index: 6;
}
.yd-navbar .yd-navbar-item span {
color: #b9b9b9 !important;
}

View File

@@ -0,0 +1,17 @@
.book-like {
.no-book {
.flex_layout(column);
margin: 2rem 0;
height: 100%;
img {
width: 58%;
}
.yd-btn {
padding: .08rem 1.1rem;
span {
font-size: .34rem;
}
}
}
}

View File

@@ -0,0 +1,70 @@
<template lang="jade">
.booklist
.yd-head(v-if="title")
p {{ title ? title : '标题未设置'}}
.more
span 查看更多
yd-navbar-next-icon
yd-list(:theme='themeType ? themeType : 4')
yd-list-item(v-for='item, key in bookList', :key='key')
img(slot='img', :src='item.img ? item.img : item.imgUrl')
span(slot='title') {{ item.title }}
yd-list-other(slot='other')
div
span.demo-list-price
em
| {{item.price ? item.price : item.introduce.substring(0,50)}}
span.demo-list-del-price {{ item.w_price }}
</template>
<script>
export default {
props: {
title: {
type: String,
required: false
},
bookList: {
type: Array,
required: true
},
themeType: {
type: Number,
required: false
}
},
created() {
},
data() {
return {
}
},
}
</script>
<style lang="less">
@import "./../../assets/less/_mixins/index";
@import "./../../assets/less/_variables/index";
.booklist {
margin-bottom: @BottomSecant;
.yd-head {
.flex_layout();
padding: 0 .14rem;
background: #fff;
height: .8rem;
p {
font-size: .3rem;
}
span {
font-size: 12px;
color: #999;
vertical-align: sub;
}
}
}
</style>

View File

@@ -0,0 +1,34 @@
<template lang="jade">
.footer
yd-tabbar(slot='tabbar' fixed :exact="false")
yd-tabbar-item(v-for='(item, index) in tabBar', :title='item.title', :link='item.link', :key='index')
yd-icon(v-bind:name='item.icons' slot='icon' custom)
</template>
<script>
import { mapActions } from "vuex";
export default {
data () {
return {
tabBar: [
{ title: '书架', link: '/like', icons: 'shuj' },
{ title: '书城', link: '/home', icons: 'shuc' },
{ title: '分类', link: '/class', icons: 'class' },
{ title: '我的', link: '/about', icons: 'about' }
]
}
},
methods: {
...mapActions([
'SetTitle'
]),
changeTitle (titles) {
this.SetTitle(titles)
}
}
}
</script>
<style lang="less" scoped>
</style>

View File

@@ -0,0 +1,25 @@
<template lang="jade">
.head
yd-navbar(slot='navbar', fontsize="17px", :title='title' fixed)
router-link(to='#', slot='right')
yd-icon(name='type' size='25px')
</template>
<script>
import { mapGetters } from "vuex";
export default {
data () {
return {
}
},
computed: {
...mapGetters({
title: 'Title'
})
}
}
</script>
<style lang="less">
</style>

View File

@@ -0,0 +1,19 @@
<template lang="jade">
yd-slider(autoplay='3000')
yd-slider-item(v-for="(n , index) in swiperList", :key="index")
a(:href='n.href')
img(:src='n.src')
</template>
<script>
export default {
props: {
swiperList: Array
}
}
</script>
<style lang="less" scoped>
</style>

View File

@@ -0,0 +1,33 @@
<template lang="jade">
.login-header
.login-header-banner
h3 {{title}}
</template>
<script>
export default {
props: ['title']
}
</script>
<style lang="less" scoped>
@import "./../../assets/less/_variables/index";
@import "./../../assets/less/_mixins/index";
.login-header {
.login-header-banner {
width: 100%;
height: 5rem;
background: @global-color;
.flex_layout(row,center);
h3 {
color: @white-color;
font-size: .48rem;
letter-spacing: .04rem;
font-weight: bolder;
}
}
}
</style>

View File

@@ -0,0 +1,87 @@
<template lang="jade">
.book-about
.about-message
img(src="./../../../assets/img/user.png", alt="")
p 编码猿
.about-setting
yd-cell-group
yd-cell-item(arrow='')
yd-icon(slot='icon', name='start', size='.42rem' custom)
span(slot='left') 我的收藏
span(slot='right') 查看收藏
yd-cell-item(arrow='')
yd-icon(slot='icon', name='night', size='.42rem' custom)
span(slot='left') 夜间模式
span(slot='right')
.line
yd-cell-item(arrow='')
yd-icon(slot='icon', name='setting', size='.42rem' custom)
span(slot='left') 设置
span(slot='right') 设置
yd-cell-item(arrow='')
yd-icon(slot='icon', name='bangzhu', size='.42rem' custom)
span(slot='left') 帮助与反馈
span(slot='right') gogo
yd-cell-item(arrow='')
yd-icon(slot='icon', name='xieyi', size='.42rem' custom)
span(slot='left') 使用协议
span(slot='right') gogo
yd-cell-item(arrow='')
yd-icon(slot='icon', name='banben', size='.42rem' custom)
span(slot='left') 版本
span(slot='right') gogo
yd-cell-item(arrow='')
yd-icon(slot='icon', name='qingchuhuancun', size='.42rem' custom)
span(slot='left') 清除缓存
span(slot='right') gogo
</template>
<script>
import { mapGetters, mapActions } from "vuex";
export default {
created() {
this.SetTitle("我的")
},
methods: {
...mapActions({
SetTitle:'SetTitle'
})
}
}
</script>
<style lang="less" scoped>
.book-about {
.about-message {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 4.4rem;
margin-top: -0.04rem;
background: #a70a0a;
img {
width: 2.1rem;
}
p {
margin-top: 20px;
font-size: 17px;
letter-spacing: 2px;
color: #fff;
}
}
.about-setting{
margin-top: 0.2rem;
.yd-cell-item{
padding: 0.1rem 0 0.1rem 0.24rem;
border-bottom: 1px solid #f3f3f3
}
}
.line{
height: 0.2rem;
background: #f2efef;
}
}
</style>

View File

@@ -0,0 +1,48 @@
<template lang="jade">
.book-class
yd-scrolltab
yd-scrolltab-panel(label='空调', icon='demo-icons-category1')
v-havebook(:bookList="bookList", :themeType='2')
yd-scrolltab-panel(label='冰箱', icon='demo-icons-category2', active='')
v-havebook(:bookList="bookList", :themeType='2')
yd-scrolltab-panel(label='洗衣机', icon='demo-icons-category3')
v-havebook(:bookList="bookList", :themeType='2')
</template>
<script>
import { mapGetters, mapActions } from "vuex";
import booklist from "./../../tpl/booklist.vue";
export default {
created() {
console.log('分类');
this.SetTitle("分类")
},
data() {
return {
bookList: [
{img: "http://img1.shikee.com/try/2016/06/23/14381920926024616259.jpg", title: "标题111标题标题标题标题", price: 156.23, w_price: 89.36},
{img: "http://img1.shikee.com/try/2016/06/21/10172020923917672923.jpg", title: "标题222标题标题标题标题", price: 256.23, w_price: 89.36},
{img: "http://img1.shikee.com/try/2016/06/23/15395220917905380014.jpg", title: "标题333标题标题标题标题", price: 356.23, w_price: 89.36}
]
}
},
components: {
'v-havebook': booklist
},
methods: {
...mapActions({
SetTitle:'SetTitle'
})
}
}
</script>
<style lang="less" scoped>
.book-class {
position: fixed;
top: 1.06rem;
bottom: 1.14rem;
width: 100%;
}
</style>

View File

@@ -0,0 +1,96 @@
<template lang="jade">
.index-info
yd-backtop
div(v-if="($route.params.id).toString() === '1' ")
//- 轮播图下面的分类
yd-grids-group(:rows='4')
yd-grids-item(v-for="(item,index) in classList", :key="index")
img(slot='icon', :src='item.src')
span(slot='text') {{ item.text }}
yd-infinitescroll(:callback='loadList', ref='infinitescrollDemo')
yd-list(theme='4', slot='list')
yd-list-item(v-for='item, key in this.getClassData', :key='key' @click.native="enterInfo(item.url)")
img(slot='img', :src='item.imgURL')
span(slot='title') {{item.title}} | {{item.author}}
yd-list-other(slot='other')
div
span.list-price
em {{item.introduce.substring(0,50)}}
span(slot='doneTip') 啦啦啦啦啦啦没有数据啦~~
img(slot='loadingTip', src='http://static.ydcss.com/uploads/ydui/loading/loading10.svg')
div(v-else-if="($route.params.id).toString() === '2' ") 2
div(v-else-if="($route.params.id).toString() === '3' ") 3
div(v-else-if="($route.params.id).toString() === '4' ") 4
div(v-else-if="($route.params.id).toString() === '5' ") 5
div(v-else='')
h2 分类id不存在
</template>
<script>
import { mapGetters, mapActions, mapMutations } from "vuex";
import booklistComponents from "./../../tpl/booklist.vue";
export default {
created() {
if (this.getClassData.length == 0) {
this.loadData()
}
},
data() {
return {
page: 1,
class: 1,
maxPage: 267,
classList: [
{ id: 1, src: require('./../../../assets/img/book-list.png'), text: '书架' },
{ id: 2, src: require('./../../../assets/img/nav-order.png'), text: '书城' },
{ id: 3, src: require('./../../../assets/img/book-like.png'), text: '推荐' },
{ id: 4, src: require('./../../../assets/img/book-setting.png'), text: '我的' }
],
title: '口碑神作',
bookList: []
}
},
methods: {
...mapActions({
SetTitle:'SetTitle',
GetClass: 'GetClassData',
}),
loadList() {
++this.page
if(this.page > this.maxPage) {
this.$refs.infinitescrollDemo.$emit('ydui.infinitescroll.loadedDone');
return;
}else {
this.loadData()
this.$refs.infinitescrollDemo.$emit('ydui.infinitescroll.finishLoad');
}
},
async loadData() {
await this.GetClass({
class: this.class,
page: this.page,
action: 'more'
})
},
enterInfo(title) {
this.$router.push({ path: '/info', query: { id: title.substring(22) }})
}
},
computed: {
...mapGetters({
getClassData: 'ClassVideoData'
})
},
components: {
'v-book': booklistComponents
}
}
</script>
<style lang="less" scoped>
</style>

View File

@@ -0,0 +1,52 @@
<template lang="jade">
.index
.index-scroll
ul
li(v-for="(item, index) in classList", :key="index")
router-link(:to="{ name: 'indexInfo', params: { id: item.type }}") {{ item.title }}
v-swiper(:swiperList="swiper")
router-view
</template>
<script>
import { mapGetters, mapActions } from "vuex";
import swiperComponents from "./../../tpl/swiper.vue";
export default {
created () {
this.SetTitle("书城")
},
data () {
return {
classList: [
{ id: '1', title: '玄幻小说', type: 1 },
{ id: '2', title: '修真小说', type: 2 },
{ id: '3', title: '都市小说', type: 3 },
{ id: '4', title: '穿越小说', type: 4 },
{ id: '5', title: '网游小说', type: 5 }
],
swiper: [
{ id: 1, href: '/index', src: 'http://statics.zhuishushenqi.com/recommendPage/15453823588110' },
{ id: 2, href: '/index', src: 'http://statics.zhuishushenqi.com/recommendPage/154538237741967' },
{ id: 3, href: '/index', src: 'http://statics.zhuishushenqi.com/recommendPage/154348118998888' }
]
}
},
methods: {
...mapActions({
SetTitle: 'SetTitle'
})
},
computed: {
...mapGetters({
indexData: 'homeData'
})
},
components: {
'v-swiper': swiperComponents
}
}
</script>
<style scoped lang='less'>
</style>

View File

@@ -0,0 +1,133 @@
<template lang="jade">
.infos
yd-navbar(style="background: #d9d9d900 !important;")
yd-navbar-back-icon(slot='left',@click.native="$router.go(-1)")
yd-icon(name="share1" size="25px" color="#b9b9b9", slot='right')
//- 头部主要信息
.info-background(:style="{ background: 'url('+url+') no-repeat center', backgroundSize: '100% 100%' }")
.info-header
.header-img
img(:src="info.imgUrl" v-if="info")
.header-info(v-if="info")
p {{info.title }}
.header-class
span {{info.author}}
span &nbsp;|&nbsp;
span 玄幻
br
span {{info.updateTime}}
//- 简介和目录
.info-introduce
p.introduce-title 简介
p.introduce-content(v-if="info") {{info.introduce.length == 0 ? '这可能是一本很精彩的小说...' : info.introduce }}
.introduce-newbook(v-if="info")
p 最新
p {{ info.newChapter.newTitle }}
//- 小说章节列表
.info-booklist(v-if="info")
yd-cell-group
yd-cell-item(arrow='', v-for="(item,index) in info.oldChapter", :key="index", @click.native="StartRead(item.chapterUrl)")
span(slot='left') {{item.chapterTitle}}
//- 加入书架 + 开始阅读
.info-read
yd-flexbox
yd-flexbox-item(:class=" isActive ? 'add-base add-bookshelf-active' : 'add-base add-bookshelf-noactive' ")(@click.native=" isActive ? addBook() : '' ") 加入书架
yd-flexbox-item.start-read(@click.native="StartRead(info.oldChapter[0].chapterUrl)") 开始阅读
yd-backtop
</template>
<script>
import { mapMutations } from "vuex";
export default {
data() {
return {
info: null,
url: null,
isActive: true
}
},
created() {
this.getInfoData()
this.checkBook()
},
methods: {
...mapMutations({
HiddenNavbar :'SET_HiddenNavbar',
HiddenTabbar :'SET_HiddenTabbar',
HiddenContent: 'SET_isContent',
SaveBookList: 'SET_BOOKLIST'
}),
async getInfoData() {
this.info = (await this.$http.get({
url: '/info',
params: {
id: this.$route.query.id
}
})).data;
// 将小说的所有章节存到vuex中
this.SaveBookList(this.info.oldChapter)
this.url = this.info.imgUrl;
},
StartRead (chapterUrl) {
this.$router.push({ path: '/read', query: { id: chapterUrl }})
},
/**
* 一进入页面就去检查这本书是否已经被用户添加书架
* 1: 没有收藏 增按钮激活,可点击能收藏
* 2已经收藏按钮灰色不可点击
*/
async checkBook () {
let check = await this.$http.post({ url: '/user/checkbook', params: { userid: (JSON.parse(localStorage.getItem('loginStatus'))).id, bookid: this.$route.query.id }});
check.data == "已收藏" ? this.isActive = false : '';
},
/**
* 添加书到书架
* @returns {Promise<void>}
*/
async addBook () {
let add = await this.$http.post({
url: '/user/addbok',
params: {
userid: (JSON.parse(localStorage.getItem('loginStatus'))).id,
bookid: this.$route.query.id
}
});
if (add.status == 200) {
this.$dialog.toast({
mes: add.data,
timeout: 1500,
icon: 'success'
});
this.isActive = false
}
}
},
beforeRouteEnter (to, from, next) {
next(vm => {
vm.HiddenNavbar(false)
vm.HiddenTabbar(false)
vm.HiddenContent(false)
})
},
beforeRouteLeave (to, from, next) {
this.HiddenNavbar(true)
this.HiddenTabbar(true)
this.HiddenContent(true)
next()
}
}
</script>
<style scoped>
</style>

View File

@@ -0,0 +1,105 @@
<template lang="jade">
.read
p(v-html="readList.content" @click="ShowSetting = !ShowSetting")
infinite-loading(@infinite="infiniteHandler")
yd-popup(v-model='ShowSetting', position="bottom", height="30%")
yd-button(type='danger', style='margin: 30px;', @click.native='ShowSetting = !ShowSetting') Close Left Popup
</template>
<script>
import { mapMutations, mapActions,mapGetters } from "vuex";
import InfiniteLoading from 'vue-infinite-loading';
export default {
data () {
return {
readList: [],
ShowSetting: false,
bookId: this.$route.query.id,
isLoad: true
}
},
created () {
this.Read();
},
methods: {
...mapMutations({
HiddenNavbar: 'SET_HiddenNavbar',
HiddenTabbar: 'SET_HiddenTabbar',
HiddenContent: 'SET_isContent'
}),
async Read () {
this.readList = (await this.$http.get({
url: '/read',
params: {
id: this.bookId
}
})).data;
this.readList.content = `<br/> <h2>${this.readList.title}</h2> <br/> ${this.readList.content}`
this.isLoad = false
document.title = this.readList.title
},
infiniteHandler() {
if(this.isLoad) {
console.log('为true')
}else {
console.log('为false')
let blist = this.getBookList
for (let i = 0; i<blist.length; i++) {
if(this.$route.query.id == blist[i].chapterUrl) {
this.bookId = blist[i + 1].chapterUrl
this.Read()
}
}
}
$state.loaded();
}
},
beforeRouteEnter (to, from, next) {
document.querySelector('body').setAttribute('style', 'background-color: #eee7e6;')
next(vm => {
vm.HiddenNavbar(false)
vm.HiddenTabbar(false)
vm.HiddenContent(false)
})
},
beforeRouteLeave (to, from, next) {
document.querySelector('body').removeAttribute('style')
this.HiddenNavbar(true)
this.HiddenTabbar(true)
this.HiddenContent(true)
next()
},
computed: {
...mapGetters({
getBookList: 'BookList'
})
},
components: {
InfiniteLoading,
}
}
</script>
<style scoped lang="less">
.read {
p {
padding: 0.2rem 0.3rem;
font-size: 16px;
}
}
</style>

View File

@@ -0,0 +1,96 @@
<template lang="jade">
.book-like
.no-book(v-if="isHaveBook")
img(src="../../../assets/img/bootjia.png", alt="没有书")
yd-button(size="small",type="danger",shape="circle") 添加书籍
.have-book(v-else)
yd-list(theme='4')
yd-list-item(v-for='item, key in bookList', :key='key' @click.native="itemAction(item,key)")
img(slot='img', :src='item.img ? item.img : item.imgUrl')
span(slot='title') {{ item.title }}
yd-list-other(slot='other')
div
span.demo-list-price
em
| {{item.price ? item.price : item.introduce.substring(0,50)}}
span.demo-list-del-price {{ item.w_price }}
yd-actionsheet(:items='myItems1', v-model='isShowActionsheet', cancel='取消')
</template>
<script>
import { mapGetters, mapActions } from "vuex";
import booklist from "./../../tpl/booklist.vue";
export default {
created() {
this.SetTitle("书架")
this.getLikeData()
},
data() {
return {
isShowActionsheet: false,
isHaveBook: false,
bookList: [],
readBook: {},
readBookIndex: null,
myItems1: [
{
label: '阅读',
callback: () => {
this.$router.push({ path: '/read', query: { id: this.readBook.oldChapter[0].chapterUrl }})
}
},
{
label: '删除',
callback: () => {
this.deleteBook()
}
}
]
}
},
methods: {
...mapActions({
SetTitle:'SetTitle'
}),
async getLikeData () {
this.bookList = (await this.$http.get({
url: '/user/getbook',
params: {
userid: (JSON.parse(localStorage.getItem('loginStatus'))).id
}
})).data;
this.bookList.length == 0 ? this.isHaveBook = true : this.isHaveBook = false
},
itemAction(e,index) {
// 显示弹窗
this.isShowActionsheet = !this.isShowActionsheet
// 存储用户点击的书
this.readBook = e
this.readBookIndex = index
},
async deleteBook() {
let delB = (await this.$http.get({
url: '/user/deletebook',
params: {
uid: (JSON.parse(localStorage.getItem('loginStatus'))).id,
bid: this.readBook.bookid
}
})).data;
this.bookList.splice(this.readBookIndex,1)
this.bookList.length == 0 ? this.isHaveBook = true : this.isHaveBook = false
}
},
components: {
'v-havebook': booklist
}
}
</script>
<style lang="less" scoped>
</style>

View File

@@ -0,0 +1,95 @@
<template lang="jade">
.login
v-header(title="登录")
.login-input
yd-cell-group
yd-cell-item
span(slot='left') 手机号
yd-input(slot='right', v-model='UserLogin.phone', regex='mobile', placeholder='手机号码')
yd-cell-item
span(slot='left') 密码
yd-input(slot='right', min="6", type='password', v-model='UserLogin.password', placeholder='密码')
yd-button-group
yd-button(@click.native="UserLoging()", size='large', bgcolor="#a70a0a", color="#fff", type='primary', shape='circle')
yd-button-group.other-setting
router-link(:to="{ name: 'userReg'}" style="float:left") 注册
a(class="forget" style="float:right") 忘记密码
</template>
<script>
/**
* 1: 首先检查 服务器是否已经登录
* 如果已经登录直接登录成功,否则手动登录
*
*/
import { mapMutations, mapActions } from "vuex";
import userheader from "./../../tpl/userheader.vue";
export default {
data() {
return {
UserLogin: {
phone: null,
password: null
}
}
},
created() {
this.SetTitle("登录")
},
methods: {
...mapMutations({
HiddenNavbar :'SET_HiddenNavbar',
HiddenTabbar :'SET_HiddenTabbar',
HiddenContent: 'SET_isContent'
}),
...mapActions([
'SetTitle'
]),
//
async UserLoging() {
let userLogin = await this.$http.post({
url: '/user/login',
params: {
name: this.UserLogin.phone,
pwd: this.UserLogin.password
}
});
if(userLogin.status == 200) {
localStorage.setItem('loginStatus', JSON.stringify(userLogin.data))
this.$router.push({ path: 'home/info/1'})
}
}
},
beforeRouteEnter (to, from, next) {
next(vm => {
vm.HiddenTabbar(false)
vm.HiddenContent(false)
})
},
beforeRouteLeave (to, from, next) {
this.HiddenTabbar(true)
this.HiddenContent(true)
next()
},
components: {
'v-header': userheader
}
}
</script>
<style lang="less" scoped>
.login {
.login-input{
.other-setting {
margin-top: .3rem;
position: fixed;
bottom: .16rem;
width: 100%;
a {
color: #a09e9e;
font-size: 15px;
}
}
}
}
</style>

View File

@@ -0,0 +1,126 @@
<template lang="jade">
.reg
v-header(title="注册")
yd-cell-group
yd-cell-item
span(slot='left') 手机号
yd-input(slot='right',ref="userPhone", regex='mobile', placeholder='手机号码', v-model="UserReg.userPhone",:required="true")
yd-cell-item
span(slot='left') 密码
yd-input(slot='right',ref="userPwd", min="6",:show-error-icon="false",:show-success-icon="false", type='password', placeholder='密码', v-model="UserReg.userPwd")
yd-cell-item
span(slot='left') 确认密码
yd-input(slot='right',ref="userAgainPwd",:show-error-icon="false",:show-success-icon="false",min="6", type='password', placeholder='确认密码', v-model="UserReg.userAgainPwd")
p(v-if="showError" class="error") {{nullTips}}}
yd-button-group
yd-button(size='large', bgcolor="#a70a0a", color="#fff", type='primary', shape='circle',@click.native="UserLogin")
yd-button-group.other-setting
a(href="#/login" style="float:left" )
a(class="forget" style="float:right") 忘记密码
</template>
<script>
import userheader from "./../../tpl/userheader.vue";
import { mapMutations, mapActions } from "vuex";
export default {
data () {
return {
showError: false,
nullTips: null,
UserReg: {
userPhone: null,
userPwd: null,
userAgainPwd: null
}
}
},
watch: {
'UserReg.userPwd' (newVal, oldVal) {
if (!this.$refs.userPwd.valid) {
this.showError = true
this.nullTips = '密码至少6位'
}else {
if (this.UserReg.userAgainPwd != this.UserReg.userPwd) {
this.showError = true
this.nullTips = '两次密码不一致'
}else {
this.showError = false
this.nullTips = null
}
}
},
'UserReg.userAgainPwd' (newVal, oldVal) {
if (newVal !== this.UserReg.userPwd) {
this.showError = true
this.nullTips = '两次密码不一致'
} else {
this.showError = false
}
}
},
created() {
this.SetTitle("注册")
},
methods: {
...mapMutations({
HiddenNavbar :'SET_HiddenNavbar',
HiddenTabbar :'SET_HiddenTabbar',
HiddenContent: 'SET_isContent'
}),
...mapActions([
'SetTitle'
]),
async UserLogin() {
if(this.$refs.userPhone.valid == true && this.showError == false) {
let userReg = await this.$http.post({
url: '/user/reg',
params: {
name: this.UserReg.userPhone,
pwd: this.UserReg.userPwd
}
});
userReg.status == 200 ? this.$router.push({ path: '/login'}) :''
}else {
console.log('error')
}
}
},
beforeRouteEnter (to, from, next) {
next(vm => {
vm.HiddenTabbar(false)
vm.HiddenContent(false)
})
},
beforeRouteLeave (to, from, next) {
this.HiddenTabbar(true)
this.HiddenContent(true)
next()
},
components: {
'v-header': userheader
},
computed: {
}
}
</script>
<style lang="less" scoped>
.other-setting {
margin-top: .3rem;
position: fixed;
bottom: .16rem;
width: 100%;
a {
color: #a09e9e;
font-size: 15px;
}
}
.error{
padding-left: 13px;
color: #a7250c;
}
</style>

View File

@@ -0,0 +1,6 @@
export default {
HttpUrl: {
// 获取小说分类的api接口
class: '/class'
}
}

View File

@@ -0,0 +1,74 @@
import Vue from 'vue'
import axios from "axios";
import { Loading, Toast } from 'vue-ydui/dist/lib.rem/dialog';
axios.defaults.baseURL = 'http://127.0.0.1:3000/api/json/1.0';
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
Loading.open("很快加载好了")
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
switch (response.data.status) {
case 404:
Toast({
mes: response.data.data,
timeout: 1500
})
break;
}
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});
export default {
/**
* get请求
* @param {*} pars
*/
get(pars) {
return new Promise(function(resolve,reject) {
axios.get(pars.url, {
params: pars.params
})
.then((response) => {
Loading.close()
resolve(response.data);
})
.catch((error) => {
reject(error);
});
})
},
/**
* post 请求
* @param {*} pars
*/
post(pars) {
return new Promise(function(resolve,reject) {
axios.post(pars.url, pars.params)
.then((response) => {
Loading.close()
resolve(response.data);
})
.catch((error) => {
reject(error);
});
})
}
}

View File

@@ -0,0 +1,34 @@
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue';
import App from './App';
import router from './router';
import Vuex from 'vuex';
import YDUI from 'vue-ydui';
import 'vue-ydui/dist/ydui.rem.css';
import vuescroll from 'vuescroll/dist/vuescroll-native';
import 'vuescroll/dist/vuescroll.css';
import http from "./http";
import store from "./vuex/index.js";
Vue.use(YDUI);
Vue.use(Vuex);
Vue.use(vuescroll);
Vue.config.productionTip = false;
Vue.prototype.$http = http;
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
});

View File

@@ -0,0 +1,141 @@
import Vue from 'vue'
import Router from 'vue-router'
import homeComponents from '~/components/view/index'
import childrenPageComponents from '~/components/view/index/children.vue'
// 分类关于
import classComponents from '~/components/view/class'
import aboutComponents from '~/components/view/about'
//书架
import likeComponents from '~/components/view/like'
// 登录注册
import LoginComponents from '~/components/view/user/login'
import RegComponents from '~/components/view/user/reg'
// 小说详情+阅读
import InfoComponents from '~/components/view/info/'
import ReadComponents from "~/components/view/info/read";
Vue.use(Router)
const router = new Router({
routes: [
// 当访问根路径时候跳转到index页面为了解决ydui yd-tabbar :exact="false" 导致的书架
// 激活类去除不掉 的问题
// 文档参考: https://router.vuejs.org/zh/api/#exact
{
path: '/',
redirect: {
path: '/like'
}
},
{
path: '/like',
name: 'like',
component: likeComponents,
meta: {
isLogin: true,
title: '书架'
}
},
{
path: '/home',
name: 'home',
component: homeComponents,
redirect: {
path: 'home/info/1'
},
children: [
{
path: 'info/:id',
name: 'indexInfo',
component: childrenPageComponents,
meta: {
isLogin: false,
title: '书城'
}
}
]
},
{
path: '/class',
name: 'class',
component: classComponents,
meta: {
isLogin: false,
title: '分类'
}
},
{
path: '/about',
name: 'about',
component: aboutComponents,
meta: {
isLogin: true,
title: '我的'
}
},
{
path: '/login',
name: 'login',
component: LoginComponents,
meta: {
isLogin: false,
title: '登录'
}
},
{
path: '/userReg',
name: 'userReg',
component: RegComponents,
meta: {
isLogin: false,
title: '注册'
}
},
{
path: '/info',
name: 'info',
component: InfoComponents,
meta: {
isLogin: false,
title: '详情'
}
},
{
path: '/read',
name: 'read',
component: ReadComponents,
meta: {
isLogin: false,
title: '阅读'
}
}
]
})
/**
* 全局导航守卫
*/
router.beforeEach((to, from, next) => {
document.title = to.meta.title
if(to.meta.isLogin) {
if(localStorage.getItem("loginStatus") == null) {
next({
path: '/login',
query: {
redirect: to.name
}
})
} else {
next()
}
}else {
next()
}
})
export default router

View File

@@ -0,0 +1,9 @@
/**
* 全局工具函数
*/
export default {
}

View File

@@ -0,0 +1,10 @@
const getters = {
ClassVideoData: state => state.home.ClassVideo,
Title: state => state.pub.NavBarTitle,
HiddenNavbar: state => state.pub.hiddenNavbar,
HiddenTabbar: state => state.pub.hiddenTabbar,
iscontent: state => state.pub.isContent,
BookList: state => state.info.BookList
}
export default getters

View File

@@ -0,0 +1,21 @@
import Vue from 'vue'
import Vuex from 'vuex'
import home from './modules/home'
import pub from './modules/public'
import info from './modules/info'
import getters from './getters'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
home,
pub,
info
},
getters
})
export default store

View File

@@ -0,0 +1,25 @@
import http from "./../../http";
import config from "./../../config";
const home = {
state: {
ClassVideo: []
},
mutations: {
SET_CLASSVIDEO: (state, data) => {
state.ClassVideo = [ ...state.ClassVideo, ...data ]
// 2 for (var i =0 ;i<data.length;i++) {
// state.ClassVideo.push(data[i])
// }
// 3 state.ClassVideo = state.ClassVideo.concat(data)
}
},
actions: {
async GetClassData({ commit }, par) {
let datas = await http.get({ url: config.HttpUrl.class, params: par })
commit('SET_CLASSVIDEO', datas)
}
}
}
export default home

View File

@@ -0,0 +1,15 @@
import http from "./../../http";
import config from "./../../config";
const info = {
state: {
BookList: []
},
mutations: {
SET_BOOKLIST: (state, data) => {
state.BookList = data
}
}
}
export default info

View File

@@ -0,0 +1,30 @@
const publics = {
state: {
NavBarTitle: "书架",
hiddenNavbar: true,
hiddenTabbar: true,
isContent: true
},
mutations: {
SET_NavBarTitle: (state, title) => {
state.NavBarTitle = title
},
SET_HiddenNavbar: (state, status) => {
state.hiddenNavbar = status
},
SET_HiddenTabbar: (state, status) => {
state.hiddenTabbar = status
},
SET_isContent: (state, status) => {
state.isContent = status
}
},
actions: {
async SetTitle({ commit }, ti) {
commit('SET_NavBarTitle', ti)
}
}
}
export default publics

View File

@@ -0,0 +1,7 @@
{
"env": {
"jest": true
},
"globals": {
}
}

View File

@@ -0,0 +1,27 @@
const path = require('path')
module.exports = {
rootDir: path.resolve(__dirname, '../../'),
moduleFileExtensions: [
'js',
'json',
'vue'
],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1'
},
transform: {
'^.+\\.js$': '<rootDir>/node_modules/babel-jest',
'.*\\.(vue)$': '<rootDir>/node_modules/vue-jest'
},
snapshotSerializers: ['<rootDir>/node_modules/jest-serializer-vue'],
setupFiles: ['<rootDir>/test/unit/setup'],
mapCoverage: true,
coverageDirectory: '<rootDir>/test/unit/coverage',
collectCoverageFrom: [
'src/**/*.{js,vue}',
'!src/main.js',
'!src/router/index.js',
'!**/node_modules/**'
]
}

View File

@@ -0,0 +1,3 @@
import Vue from 'vue'
Vue.config.productionTip = false

View File

@@ -0,0 +1,11 @@
import Vue from 'vue'
import HelloWorld from '@/components/HelloWorld'
describe('HelloWorld.vue', () => {
it('should render correct contents', () => {
const Constructor = Vue.extend(HelloWorld)
const vm = new Constructor().$mount()
expect(vm.$el.querySelector('.hello h1').textContent)
.toEqual('Welcome to Your Vue.js App')
})
})

View File

@@ -0,0 +1,19 @@
1点击进入详情(实现)
3用户的登录注册
2实现对小说收藏(添加进入书架)
4小说的阅读(实现)
/**
* 设计思路:
* 1用户登录的时候需要传递账号密码
* 2同时还必须提交客户端的ip地址
* 3服务器session存储用户登录成功后的状态值
* 4将session和ip地址绑定
*
* 5防止表单注入过滤接口参数
*
*/