Commit fbaf2d82 authored by 郭铭瑶's avatar 郭铭瑶 🤘

初始化项目

parent 44f0dd30
{
"presets": [
["env", {
"modules": false,
"useBuiltIns": "entry",
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}],
"stage-2"
],
"plugins": [
"transform-vue-jsx",
"transform-runtime",
["import", {
"libraryName": "ant-design-vue",
"libraryDirectory": "es",
"style": "css",
}]
]
}
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
/build/
/config/
/dist/
/*.js
// https://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parserOptions: {
parser: 'babel-eslint'
},
env: {
browser: true,
es6: true,
},
// 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.
extends: ['plugin:vue/essential'],
// required to lint *.vue files
plugins: [
'vue'
],
// add your custom rules here
rules: {
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
"indent": [
"error",
2
],
"linebreak-style": [
"error",
"unix",
],
"quotes": [
"error",
"single",
],
"semi": [
"error",
"never",
],
"no-console": 0,
}
}
.DS_Store
node_modules/
/dist/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
// 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": {}
}
}
# 框架介绍
## 命令行说明
> 执行以下打包命令可分别打生产环境、SIT环境、UAT环境的包。
```zsh
npm run build
npm run build:sit
npm run build:uat
```
> 执行以下命令可以检查、并自动修复一些代码格式错误,如空格、分号等,以保持代码格式统一。同时我加入了指令,会在commit到git时自动执行此命令。相关代码规则可在[.eslintrc.js](./.eslintrc.js)中配置。
```zsh
npm run lint
```
## [Ant Design Vue](https://vue.ant.design/docs/vue/introduce/) 说明
> 使用ant design vue框架中的组件时,需要在[/src/main.js](/src/main.js)中手动地import和use。这看起来有点麻烦,但其实避免了import了整个包却只使用了部分组件造成的打包体积过大和性能的浪费。
```javascript
/*main.js中*/
/** 省略 **/
import {
Button,
Card,
} from 'ant-design-vue'
Vue.use(Button)
Vue.use(Card)
/** 省略 **/
```
```html
<!-- 使用 -->
<a-card>
<h1>Example</h1>
<a-button type="primary">Btn1</a-button>
<a-button type="dashed">Btn2</a-button>
<a-button type="danger">Btn3</a-button>
</a-card>
```
## 封装方法说明
- ## this.$cookie
> 封装了js-cookie方法,用于判断electron状态下使用localstorage替换js-cookie。
```javascript
this.$cookie.set('cookieName', 'cookieData')
this.$cookie.get('cookieName')
this.$cookie.remove('cookieName')
```
- ## this.$api
> 请求的api集合,可自动根据不同的环境(即process.env.NODE_ENV)切换对应的请求根地址。详情可查看[/src/server/ajax.js](/src/server/api.js)
- ## this.$ajax
> 将axios进行二次封装的请求方法。详细信息可查看[/src/server/ajax.js](/src/server/ajax.js)
```javascript
/**
* @param {Object} args [请求的参数,包含如下]
* @param {String} url [请求地址]
* @param {Object} params [请求参数]
* @param {String} contentType [请求头,默认为'application/json;charset=UTF-8']
* @param {Boolean} hideLoading [隐藏请求时的loading图,默认为false]
*/
this.$ajax.get(args)
this.$ajax.post(args)
this.$ajax.put(args)
this.$ajax.delete(args)
//示例
this.$ajax.post({
url: this.$api.GET_TOKEN,
params: {
userName: 'test',
},
contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
}).then(res => {
this.$cookie.set('token', res.access_token)
this.$cookie.set('refresh_token', res.refresh_token)
})
/**
* 一次性发起多个请求
* @param {Function} ajaxs [请求函数]
*/
this.$ajax.all(ajaxs)
// 示例
this.$ajax.all(
this.$ajax.get({url: '/static/user-info.json'}),
this.getPermission(),
).then(res => {
console.log(res)
})
getPermission() {
return this.$ajax.get({url: '/static/permission.json'})
}
```
- ## this.$com
> 公共方法,详细方法见文件[/src/util/common.js](/src/util/common.js)的方法注释。
- ## this.$permission
> 传入权限编码,判断权限的方法。也可以使用v-permission自定义指令。详情见[/src/util/permission-control.js](/src/util/permission-control.js)和[/src/util/permission-filter.js](/src/util/permission-filter.js)
```html
<div v-if="$permission('code')">测试</div>
<div v-permission="'code'">测试</div>
```
> 请求、获取、判断权限编码列表,并据此设置权限菜单详见文件[/src/util/mixins.js](/src/util/mixins.js)。当登录或者刷新页面时都会调用此文件中的方法。
'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'
))
})
})
'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)
}
}
'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')
})
}
}
'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'
}
}
'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: ['babel-polyfill', './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'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src'),
}
},
module: {
rules: [
...(config.dev.useEslint ? [createLintingRule()] : []),
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
},
{
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'
}
}
'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)
}
})
})
'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 = require('../config/prod.env')
let env = require('../config/prod.env')
if (process.env.NODE_ENV === 'sit') {
env = require('../config/sit.env')
} else if (process.env.NODE_ENV === 'uat') {
env = require('../config/uat.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: 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
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"'
})
'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: true,
// 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
}
}
'use strict'
module.exports = {
NODE_ENV: '"production"'
}
'use strict'
module.exports = {
NODE_ENV: '"sit"'
}
'use strict'
module.exports = {
NODE_ENV: '"uat"'
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>demo</title>
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"name": "demo",
"version": "1.0.0",
"description": "A Vue.js project",
"author": "GuoMingyao <missgmy@yahoo.com>",
"private": true,
"scripts": {
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
"start": "npm run dev",
"lint": "eslint --fix --ext .js,.vue src",
"build": "cross-env NODE_ENV='production' node build/build.js",
"build:sit": "cross-env NODE_ENV='sit' node build/build.js",
"build:uat": "cross-env NODE_ENV='uat' node build/build.js"
},
"pre-commit": [
"lint"
],
"dependencies": {
"ant-design-vue": "^1.3.13",
"axios": "^0.19.0",
"babel-polyfill": "^6.26.0",
"js-cookie": "^2.2.0",
"moment": "^2.24.0",
"qs": "^6.7.0",
"vue": "^2.5.2",
"vue-router": "^3.0.1",
"vuex": "^3.1.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-loader": "^7.1.1",
"babel-plugin-import": "^1.12.0",
"babel-plugin-syntax-jsx": "^6.18.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",
"cross-env": "^5.2.0",
"css-loader": "^0.28.0",
"eslint": "^4.15.0",
"eslint-friendly-formatter": "^3.0.0",
"eslint-loader": "^1.7.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",
"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",
"pre-commit": "^1.2.2",
"rimraf": "^2.6.0",
"semver": "^5.3.0",
"shelljs": "^0.7.6",
"uglifyjs-webpack-plugin": "^1.1.1",
"url-loader": "^0.5.8",
"vue-loader": "^13.3.0",
"vue-style-loader": "^3.0.1",
"vue-template-compiler": "^2.5.2",
"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"
]
}
<template>
<div id="app">
<a-locale-provider :locale="zh_CN">
<router-view/>
</a-locale-provider>
</div>
</template>
<script>
import zh_CN from 'ant-design-vue/lib/locale-provider/zh_CN'
export default {
name: 'App',
data() {
return {
zh_CN,
}
},
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #2c3e50;
width: 100%;
height: 100%;
}
</style>
<template>
<a-form :form="form">
<slot name="title"/>
<a-row v-for="(row, rowIndex) in layout" :key="rowIndex">
<a-col v-for="(item, key) in row" :key="key" :span="item.width" :offset="item.offset || 0" v-show="!item.hidden">
<!-- 不想包裹在a-form-item中可以设置custom为true, 否则render的组件在ActiveFormItem中定义 -->
<template v-if="item.custom && item.render">
<component :is="custom(key, item.render, item.props)"/>
</template>
<ActiveFormItem
v-else
:entry="key"
:model="model"
:item="item"
:labelWidth="labelWidth"
/>
</a-col>
</a-row>
<slot />
</a-form>
</template>
<script>
import Vue from 'vue'
import moment from 'moment'
import ActiveFormItem from './ActiveFormItem'
export default {
name: 'ActiveForm',
components: {
ActiveFormItem
},
props: {
layout: {
type: Array,
required: true
},
model: {
type: Object,
default () {
return {}
}
},
labelWidth: {
type: Number,
default () {
return 5
}
}
},
created () {
this.filterDateItem()
},
data () {
return {
form: this.$form.createForm(this, {
// 当表单值变化时同时赋给model
onValuesChange: (e, val) => {
this.model = Object.assign(this.model, this.operateDateItem(val, true))
}
}),
dateItems: {}
}
},
mounted () {
const model = this.filterDataModel(this.model)
// 根据model初始化表单值
this.form.setFieldsValue(this.operateDateItem(model, false))
},
methods: {
custom(entry, render, props) {
return Vue.component(entry, {
render: render,
props: props,
})
},
// 表单验证,上级组件可以通过this.$refs来调用此函数
validate (callback) {
this.form.validateFields((err, values) => {
if (err) {
this.$com.getFormValidErrTips(this, err) // 这边是后来加的需求,说要全局弹窗
}
callback(err, values)
})
},
// 筛选layout中的日期组件
filterDateItem () {
const result = {}
this.layout.forEach(item => {
for (const key in item) {
if (item[key].type && (item[key].type == 'date' || item[key].type == 'daterange')) {
result[key] = item[key]
}
}
})
this.dateItems = result
},
// 由于antd的日期组件都是moment格式,这里进行了转化成字符串
operateDateItem (obj, isMomentToString) {
const model = { ...obj }
for (const key in model) {
const dateItem = this.dateItems[key]
if (dateItem) {
if (dateItem.type == 'date') {
if (isMomentToString) {
if (!moment.isMoment(model[key])) return model
model[key] = moment(model[key]).format(dateItem.format || 'YYYY-MM-DD')
} else {
model[key] = moment(model[key], dateItem.format || 'YYYY-MM-DD')
}
} else if (dateItem.type == 'daterange') {
if (isMomentToString) {
if (!moment.isMoment(model[key][0]) || !moment.isMoment(model[key][1])) return model
model[key] = [moment(model[key][0]).format(dateItem.format || 'YYYY-MM-DD'), moment(model[key][1]).format(dateItem.format || 'YYYY-MM-DD')]
} else {
model[key] = [moment(model[key][0], dateItem.format || 'YYYY-MM-DD'), moment(model[key][1], dateItem.format || 'YYYY-MM-DD')]
}
}
}
}
return model
},
// 过滤掉layout中不存在的字段,防止You cannot set a form field before rendering a field associated with the value.的错误
filterDataModel (model) {
const keys = Object.keys(model)
if (keys.length <= 0) return {}
const list = []
if (this.layout.length > 0) {
this.layout.forEach(item => {
list.push(...Object.keys(item))
})
}
const result = {}
keys.forEach(key => {
if (list.indexOf(key) >= 0) {
result[key] = model[key]
}
})
return result
}
},
watch: {
model (cur, past) {
// 通过监听model来判断reset表单或给表单重新设置值
const keys = Object.keys(cur)
const result = this.filterDataModel(cur)
if (keys.length <= 0) {
this.form.resetFields()
} else {
this.form.resetFields()
this.form.setFieldsValue(this.operateDateItem(result, false))
}
}
}
}
</script>
<template>
<a-form-item class="activeform-item" :label-col="labelCol" :wrapper-col="wrapperCol" :label="item.label">
<a-input
v-if="item.type == 'input'"
v-decorator="validate"
:placeholder="placeholder"
:disabled="item.disabled" />
<a-textarea
v-if="item.type == 'textarea'"
v-decorator="validate"
:placeholder="placeholder"
:disabled="item.disabled" />
<a-checkbox-group
v-if="item.type == 'checkbox'"
v-decorator="validate"
:options="item.options"
:disabled="item.disabled" />
<a-radio-group
v-if="item.type == 'radio'"
v-decorator="validate"
:options="item.options"
:disabled="item.disabled" />
<a-select
v-if="item.type == 'select'"
v-decorator="validate"
allowClear
:placeholder="placeholder"
:disabled="item.disabled">
<a-select-option
v-for="option in item.options"
:key="option.value"
:value="option.value">
{{option.label}}
</a-select-option>
</a-select>
<a-cascader
v-if="item.type == 'cascader'"
v-decorator="validate"
allowClear
:options="item.options"
:placeholder="placeholder"
:disabled="item.disabled" />
<a-date-picker
v-if="item.type == 'date'"
style="width: 100%"
v-decorator="validate"
:format="item.format"
allowClear
:disabledDate="item.disabledDate || null"
:placeholder="placeholder"
:disabled="item.disabled" />
<a-range-picker
v-if="item.type == 'daterange'"
style="width: 100%"
v-decorator="validate"
:format="item.format"
allowClear
:disabledDate="item.disabledDate || null"
:placeholder="placeholder"
:disabled="item.disabled" />
<a-upload
v-if="item.type == 'upload'"
multiple
v-decorator="validate"
:customRequest="handleRequest"
@change="handleChange"
:remove="item.remove"
accept='.jpg,.jpeg,.png,.gif,.doc,.docx,.xlsx,.xls,.xlsm,.txt,.pdf'
:beforeUpload='item.beforeUpload'>
<a-button>
<a-icon type="upload" /> {{item.txt || '上传'}}
</a-button>
</a-upload>
<a-button class="ActiveForm-view-btn" v-if="item.type == 'view'" v-decorator="validate" @click="handleClick">
<a v-if="model[entry] && model[entry].fileType == 'file'" :href='model[entry].url' target="_blank">{{model[entry] && model[entry].name}}</a>
<span v-else-if="model[entry] && model[entry].fileType == 'pic'">{{model[entry] && model[entry].name}}</span>
<span v-else>{{model[entry] && model[entry].name}}</span>
</a-button>
<span v-if="item.type == 'text'" v-decorator="validate">
{{item.formatter ? item.formatter(model[entry]) : model[entry]}}
</span>
<template v-if="item.render">
<component :is="component" v-decorator="validate"/>
</template>
</a-form-item>
</template>
<script>
import Vue from 'vue'
export default {
name: 'ActiveFormItem',
props: {
entry: {
type: String,
required: true,
},
item: {
type: Object,
required: true,
},
model: {
type: Object,
default() {
return {}
}
},
labelWidth: {
type: Number,
default() {
return 5
}
},
},
data() {
return {
curData: null,
component: null,
}
},
created() {
if (this.item.render) {
this.component = Vue.component(this.entry, {
render: this.item.render,
props: this.item.props,
})
}
},
methods: {
handleRequest(obj) {
// 这里的obj是用来onProgress、onSuccess、onError的
this.$nextTick(() => {
this.item.customRequest(this.curData.file, obj)
})
},
handleChange(data, list) {
// 这里的data是用来响应改变model数据的
this.curData = data
},
// 点击查看文件按钮的回调
handleClick() {
this.item.onClick(this.model[this.entry].url)
},
// 上传文件的过滤,防止类型错误的报错
normFile(e) {
if (Array.isArray(e)) return e
return e && e.fileList
},
},
computed: {
// 默认表单验证
validate() {
if (this.item.type == 'checkbox') {
// 如果是CheckBox的话初始化要是个数组
return [this.entry, Object.assign(this.item.validate || {}, {initialValue: []})]
}
if (this.item.type == 'upload') {
return [this.entry, Object.assign(this.item.validate || {}, {valuePropName: 'fileList' , getValueFromEvent: this.normFile})]
}
return [this.entry, this.item.validate || {}]
},
// 默认placeholder
placeholder() {
const item = this.item
if (item.placeholder) {
return item.placeholder
}
if (item.type == 'input' || item.type == 'textarea') {
return '请输入'
}
if (item.type == 'daterange') {
return ['开始日期', '结束日期']
}
return '请选择'
},
labelCol() {
return {
style: {
width: `${this.labelWidth}px`
},
}
},
wrapperCol() {
return {
style: {
display: 'inline-block',
width: `calc(90% - ${this.labelWidth}px)`
}
}
}
}
}
</script>
<style scoped>
.ActiveForm-view-btn {
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.activeform-item.ant-row.ant-form-item {
display: flex;
}
</style>
/** ActiveForm 使用示例 */
// 首先在入口文件引入并use组件
// import ActiveForm from '@/components/ActiveForm'
// Vue.use(ActiveForm)
<template>
<a-card>
<ActiveForm :layout="layout" :label-width="100" ref="exampleForm" :model="model">
<div slot="title">
<h2>ActiveForm Title(可选, 样式自己定)</h2>
</div>
<div style="text-align:right">
<a-button @click="handleSearch" type="primary">查询</a-button>
<a-button @click="handleReset">重置</a-button>
</div>
</ActiveForm>
</a-card>
</template>
<script>
export default {
name: 'ExampleComponent',
data() {
return {
layout: [
{
example1: {
label: '输入',
type: 'input',
width: 8,
validate: {
rules: [{required: true, message: '请输入'}]
}
},
example2: {
label: '单选',
type: 'radio',
width: 8,
options: [
{label: '男', value: '1'},
{label: '女', value: '0'},
]
},
example3: {
label: '选择',
type: 'select',
width: 8,
options: [
{label: '苹果', value: '苹果'},
{label: '香蕉', value: '香蕉'},
],
disabled: true
},
example4: {
label: '日期',
type: 'date',
width: 8,
validate: {
rules: [{required: true, message: '请选择日期'}]
}
},
example5: {
label: '日期区间',
type: 'daterange',
width: 8,
validate: {
rules: [{required: true, message: '请选择'}]
}
},
example6: {
label: '级联',
type: 'cascader',
width: 8,
options: [{
value: 'zhejiang',
label: 'Zhejiang',
children: [{
value: 'hangzhou',
label: 'Hangzhou',
children: [{
value: 'xihu',
label: 'West Lake',
}],
}],
}, {
value: 'jiangsu',
label: 'Jiangsu',
children: [{
value: 'nanjing',
label: 'Nanjing',
children: [{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
}],
}],
}]
},
example7: {
label: '多选框',
type: 'checkbox',
width: 8,
options: [
{label: '龙', value: '龙'},
{label: '蛇', value: '蛇'},
],
validate: {
rules: [{required: true, message: '请选择'}]
}
},
example8: {
label: '查看文件',
type: 'view',
width: 8,
onClick: this.handleClick, // 点击后触发的回调,返回对应的url
},
},
{
example9: {
label: '上传',
type: 'upload',
txt: '上传文件', // 上传按钮的名字,不传的话默认是‘上传’
width: 8,
remove: this.remove, // remove动作会自动完成,没有其他特殊要求的操作可以不用调用了
customRequest: this.customRequest, // 上传请求
beforeUpload: this.beforeUpload, // 上传前的校验,没有其他特殊要求的操作可以不用调用了
validate: {
rules: [{required: true, message: '请上传'}]
}
},
example10: {
label: '文字',
type: 'text',
width: 8,
formatter: (val) => val += '(进行格式化处理)'
},
example11: {
label: 'test',
width: 8,
render:(h) => {
// render自定义组件,会比较麻烦
return h('div', [
h('p', '测试render2个'),
h('a-select', {
props: {
placeholder: 'placeholder',
allowClear: true,
options: [{value: 'test', label: '测试render select'}],
},
on: {
select(val) {
console.log('select-change', val)
}
},
style: 'color: red',
})
])
},
}
}
],
model: {
example4: '2019/08/23',
example5: ['2019/08/23', '2019/08/24'],
example7: ['龙'],
example8: {
name: 'accounts.xlsx',
fileType: 'file', // file为新开页下载,pic根据你的event回调来定
url: 'http://iftp.omniview.pro/temp/1567069629359-634052a98b43d554976a440bf07a35af.xlsx',
},
example9: [
{
name: 'accounts.xlsx',
objId: null,
response: null,
status: null,
type: null,
uid: 'f58ba55c2ce847a0bc7ea0ca74fadcb9',
url: 'http://iftp.omniview.pro/temp/1567069629359-634052a98b43d554976a440bf07a35af.xlsx',
}
],
example10: '纯展示数据用',
},
}
},
methods: {
handleSearch() {
console.log('example-model', this.model)
this.$refs.exampleForm.validate(err => {
if (err) return
// TODO 这里做接下来的其他操作
this.model.example10 = JSON.stringify(this.model)
})
},
handleReset() {
this.model = {
example8: {
name: 'accounts.xlsx',
fileType: 'file',
url: 'http://iftp.omniview.pro/temp/1567069629359-634052a98b43d554976a440bf07a35af.xlsx',
},
}
},
// 上传的请求
customRequest(data, fn) { // data是数据,可修改data来同步更新model;fn用来调用onProgress、onSuccess、onError这些函数
setTimeout(() => { // 模拟请求完成后的操作
// 这里可以修改data的一些所需的字段值,比如插入url什么的
data.url = 'http://www.baidu.com'
// !!有一点不同的是没必要再手动插入model中了,model会自动更新
fn.onSuccess()
}, 500)
},
// remove动作会自动完成,如果没有其他特殊要求的操作可以去掉了
remove(data) {
console.log('remove', data)
},
// 上传前的校验,没有其他特殊要求的操作可以去掉了
beforeUpload(data) {
console.log('before', data)
},
handleClick(data) {
console.log('click', data)
},
}
}
</script>
import ActiveFormComponent from './ActiveForm'
export default (Vue) => {
Vue.component(ActiveFormComponent.name, ActiveFormComponent)
}
<template>
<a-table
:size="size"
:rowKey="rowKey"
:columns="layout"
:dataSource="data"
:bordered="bordered"
:rowClassName="setClassName"
:rowSelection="rowSelections"
:customRow="customRow"
:pagination="pagination"
@change="handleTableChange"
>
<template v-for="item in renderItems" :slot="item.dataIndex" slot-scope="text, record">
<a v-if="item.type === 'link'" :key="item.dataIndex" @click="item.onClick(record)">{{ text || item.linkText }}</a>
<span v-else-if="item.type === 'date'" :key="item.dataIndex">{{ $com.formatDate(text) }}</span>
<span v-else-if="item.type === 'money'" :key="item.dataIndex">{{ $com.toMoney(text) }}</span>
<a-input
v-else-if="item.type === 'input'"
v-model="record[item.dataIndex]"
:disabled="item.disabled"
:placeholder="item.placeholder"
style="width: 100%;"
:key="item.dataIndex"
/>
<a-select
v-else-if="item.type === 'select'"
v-model="record[item.dataIndex]"
:disabled="item.disabled"
:placeholder="item.placeholder"
allowClear
style="width: 100%;"
:key="item.dataIndex"
>
<a-select-option
v-for="option in item.options"
:key="option.value"
:value="option.value"
>{{ option.label }}</a-select-option>
</a-select>
<a-radio-group
v-if="item.type === 'radio'"
v-model="record[item.dataIndex]"
:options="item.options"
:disabled="item.disabled"
:key="item.dataIndex"
/>
</template>
<template slot="footer">
<slot name="footer" />
</template>
<template slot="title">
<slot name="title" />
</template>
<template v-for="item in slotItems" :slot="item.scopedSlots.customRender" slot-scope="text, record, index">
<slot :name="item.scopedSlots.customRender" :text="text" :record="record" :index="index" />
</template>
</a-table>
</template>
<script>
export default {
name: 'ActiveTable',
props: {
columns: {
type: Array,
default() {
return []
}
},
rowKey: {
type: String,
default: ''
},
data: {
type: Array,
default() {
return []
}
},
size: {
type: String,
default: 'small'
},
bordered: {
type: Boolean,
default: false,
},
stripe: {
// 是否显示斑马纹
type: Boolean,
default: false,
},
rowSelect: {
// 开启单行选择
type: Boolean,
default: false,
},
multiSelect: {
// 开启多选
type: Boolean,
default: false
},
multiSelectDisabled: {
// 开启多选后, 是否disable多选的checkbox
type: Boolean,
default: false
},
multiSelectDefaultChecked: {
// 开启多选后,根据此key来判断每行默认选中状态
type: [Boolean, String, Function],
default: ''
},
rowSelection: {
type: Object,
default: () => {
return {}
}
},
showPager: {
type: Boolean,
default: false,
},
total: {
type: Number,
},
currentPage: {
type: Number,
default: 1,
},
pageSize: {
type: Number,
default: 10,
}
},
data() {
return {
selectedRowKeys: [],
selectedRows: {},
renderItems: [],
slotItems: [],
}
},
methods: {
setClassName(record, index) {
if (this.selectedRowKeys.indexOf(record[this.rowKey]) >= 0 && this.rowSelect) {
return 'selected-row'
} else {
if (!this.stripe) {
return ''
}
return index % 2 === 1 ? 'odd' : 'even'
}
},
handleTableChange(pagination, filters, sorter) {
this.$emit('on-filter-change', filters)
this.$emit('on-page-change', pagination)
},
customRow(record) {
if (!this.rowSelect) return {}
return {
props: {},
on: {
click: () => {
// 选中项
this.selectedRows = record
// 选中项主键
this.selectedRowKeys = [record[this.rowKey]]
this.$emit('on-select-change', [record[this.rowKey]], record)
}
}
}
},
onSelectChange(selectedRowKeys, selectedRows) {
this.$emit('on-select-change', selectedRowKeys, selectedRows)
},
// 开启多选后 - 选择框的默认属性配置
getCheckboxProps(record) {
return {
props: {
defaultChecked: record[this.multiSelectDefaultChecked],
disabled: this.multiSelectDisabled
}
}
}
},
computed: {
rowSelections() {
if (!this.multiSelect) {
if (this.rowSelection.hasOwnProperty('type')) {
return { getCheckboxProps: this.getCheckboxProps, type: this.rowSelection.type }
} else {
return
}
} else {
return { onChange: this.onSelectChange, getCheckboxProps: this.getCheckboxProps }
}
},
pagination () {
if (!this.showPager) return false
return { showQuickJumper: true, total: this.total, current: this.currentPage, pageSize:this.pageSize }
},
layout() {
/* eslint-disable */
this.selectedRowKeys = this.data.length > 0 ? [this.data[0][this.rowKey]] : []
this.selectedRows = this.data.length > 0 ? this.data[0] : {}
const columns = [...this.columns]
columns.forEach(item => {
if (item.type) {
item.scopedSlots = { customRender: item.dataIndex }
this.renderItems.push(item)
} else {
if (item.scopedSlots) {
this.slotItems.push(item)
}
}
})
return columns
}
}
}
</script>
<template>
<ActiveTable
rowKey="id"
:columns="columns"
:data="list"
@on-page-change="test"
@on-select-change="select"
:currentPage="currentPage"
:total="total"
showPager
>
<div slot="test" slot-scope="{ text, record }">
<span style="color:red">{{ record.id }}</span>
</div>
</ActiveTable>
</template>
<script>
export default {
name: 'TableExample',
data () {
return {
total: 30,
currentPage: 1,
columns: [{
title: 'Test',
dataIndex: 'test',
scopedSlots: { customRender: 'test' }
}, {
title: 'Name',
dataIndex: 'name',
type: 'link',
align: 'center',
onClick: this.testClick
}, {
title: 'Gender',
dataIndex: 'gender',
align: 'center',
type: 'input',
placeholder: '请输入',
filterMultiple: false,
filters: [
{ text: 'Male', value: 'male' },
{ text: 'Female', value: 'female' }
]
}, {
title: 'Email',
dataIndex: 'email',
align: 'center',
type: 'select',
placeholder: '请选择',
options: [
{ label: 'qq', value: '@qq.com' },
{ label: 'gmail', value: '@gmail.com' }
]
}],
list: [
{ id: '1', name: 'test', gender: 'male', email: '@qq.com' },
{ id: '2', name: 'test', gender: 'male', email: '@qq.com' },
{ id: '3', name: 'test', gender: 'female', email: '@qq.com' },
{ id: '4', name: 'test', gender: 'male', email: '@qq.com' }
]
}
},
methods: {
log (a, b) {
console.log(a, b)
},
test ({ current }) {
console.log(current)
this.currentPage = current
},
select (a, b) {
console.log('select', a, b)
},
testClick (data) {
console.log('click', data)
}
}
}
</script>
import ActiveTableComponent from './ActiveTable'
export default (Vue) => {
Vue.component(ActiveTableComponent.name, ActiveTableComponent)
}
// 整体布局文件
<template>
<a-layout id="layout">
<Loader />
<a-layout-sider breakpoint="lg" collapsedWidth="0">
<div class="logo" />
<a-menu mode="vertical" theme="dark" style="text-align:left;">
<a-sub-menu v-for="menu in menus" :key="menu.name">
<span slot="title"><a-icon :type="menu.meta.icon" /><span>{{menu.meta.title}}</span></span>
<template v-if="menu.children && menu.children.length > 0">
<a-menu-item
v-for="child in menu.children"
:key="child.name"
@click="$router.push({name: child.name})">
{{child.meta.title}}
</a-menu-item>
</template>
</a-sub-menu>
</a-menu>
</a-layout-sider>
<a-layout>
<a-layout-header :style="{ background: '#fff', padding: 0 }">
<div style="display: flex; align-items: center;justify-content: space-between; padding: 0 1rem;">
<NavBar />
<div>
<a-dropdown>
<a href="#">
<a-icon type="user" /> 测试用户 <a-icon type="down" />
</a>
<a-menu slot="overlay" @click="handleClick">
<a-menu-item key="1">个人中心</a-menu-item>
<a-menu-item key="2">退出登录</a-menu-item>
</a-menu>
</a-dropdown>
</div>
</div>
</a-layout-header>
<a-layout-content :style="{ margin: '24px 16px 0' }">
<div :style="{ padding: '24px', background: '#fff', minHeight: '98%' }">
<router-view :key="$route.path"/>
</div>
</a-layout-content>
</a-layout>
</a-layout>
</template>
<script>
import NavBar from '@/components/Navbar/navbar'
import Loader from '@/components/Loader/loader'
export default {
name: 'Layout',
components: {
NavBar,
Loader,
},
computed: {
menus() {
return this.$store.state.menuList
}
},
methods: {
handleClick({key}) {
if (key == 1) {
this.$router.push({name: 'person'})
}
if (key == 2) {
this.$cookie.remove('token')
this.$router.replace({name: 'login'})
}
}
}
}
</script>
<style>
#layout {
width: 100%;
height: 100%;
}
#layout .logo {
height: 64px;
background: #00284e;
width: 100%;
}
</style>
<template>
<div class="loader" v-show="$store.state.showLoading">
<a-spin :tip="msg" :spinning="$store.state.showLoading" size="large"/>
</div>
</template>
<script>
export default {
name: 'Loader',
props: {
msg: {
type: String,
default: '加载中...',
}
}
}
</script>
<style scoped>
.loader {
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
background-color: rgba(0,0,0,0.1);
display: flex;
align-items: center;
justify-content: center;
z-index: 999;
}
</style>
<template>
<div class="header">
<a-breadcrumb>
<a-breadcrumb-item v-for="item in list" :key="item.name">
<router-link v-if="checkPath(item.path)" :to="item.path">{{item.name}}</router-link>
<span v-else>{{item.name}}</span>
</a-breadcrumb-item>
</a-breadcrumb>
</div>
</template>
<script>
// 不够严谨,临时制造,需要改进
export default {
name: 'NavBar',
data() {
return {
list: [],
}
},
mounted() {
let list = this.$cookie.get('NavbarList')
if (list && list.length > 0) {
list = JSON.parse(list)
if (this.$route.path != list[list.length - 1].path) {
this.list = [{name: '首页', path: '/'}]
return
}
this.list = list
}
},
methods: {
checkPath(path) {
return this.list[0].path === path
},
},
watch: {
$route(to, from) {
const filter = (item) => {
return item.path == to.path
}
const index = this.list.findIndex(filter)
if (index >= 0) {
this.list = this.list.slice(0, index + 1)
} else {
if (to.matched[1].parent.path) {
this.list = [{
name: to.matched[1].parent.meta.title,
path: to.matched[1].parent.path
}]
}
if(this.$route.meta.title){
this.list.push({
name: this.$route.meta.title,
path: this.$route.path,
})
}
if (to.path.indexOf('home') >= 0) {
this.list = [{name: '首页', path: '/'}]
}
}
if (to.path.indexOf('home') < 0) {
this.list.unshift({name: '首页', path: '/'})
}
if (to.path.indexOf('person') >= 0) {
this.list = [{name: '首页', path: '/'}, {name: '个人中心', path: '/person'}]
}
const NavbarList = JSON.stringify(this.list)
this.$cookie.set('NavbarList', NavbarList)
}
},
}
</script>
<style scoped>
.header {
display: flex;
align-items: center;
height: 100%;
}
</style>
// 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 'babel-polyfill'
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
import ajax from './server/ajax'
import api from './server/api'
import cookie from './util/local-cookie'
import common from './util/common'
import {
Button,
message,
Spin,
Layout,
Menu,
Icon,
Breadcrumb,
Form,
Input,
InputNumber,
Card,
Dropdown,
Row,
Col,
Checkbox,
Select,
Alert,
Table,
Divider,
Upload,
Modal,
badge,
Tree,
Tabs,
DatePicker,
skeleton,
pagination,
Tag,
Badge,
TreeSelect,
Radio,
Cascader,
LocaleProvider,
Steps,
Anchor,
Collapse,
Popconfirm,
Progress,
Switch,
Calendar,
BackTop,
Carousel,
Tooltip,
} from 'ant-design-vue'
import ActiveForm from '@/components/ActiveForm'
import ActiveTable from '@/components/ActiveTable'
// 由于日期组件默认是英文的,需要本地化
import moment from 'moment'
import 'moment/locale/zh-cn'
moment.locale('zh-cn')
Vue.use(ActiveForm)
Vue.use(ActiveTable)
Vue.use(Button)
Vue.use(Spin)
Vue.use(Layout)
Vue.use(Menu)
Vue.use(Icon)
Vue.use(Breadcrumb)
Vue.use(Form)
Vue.use(Input)
Vue.use(InputNumber)
Vue.use(Card)
Vue.use(Dropdown)
Vue.use(Row)
Vue.use(Col)
Vue.use(Checkbox)
Vue.use(Select)
Vue.use(Alert)
Vue.use(Table)
Vue.use(Divider)
Vue.use(Upload)
Vue.use(Modal)
Vue.use(badge)
Vue.use(skeleton)
Vue.use(Tree)
Vue.use(Tabs)
Vue.use(DatePicker)
Vue.use(pagination)
Vue.use(Tag)
Vue.use(Badge)
Vue.use(TreeSelect)
Vue.use(Radio)
Vue.use(Cascader)
Vue.use(LocaleProvider)
Vue.use(Steps)
Vue.use(Anchor)
Vue.use(Collapse)
Vue.use(Popconfirm)
Vue.use(Progress)
Vue.use(Switch)
Vue.use(Calendar)
Vue.use(BackTop)
Vue.use(Carousel)
Vue.use(Tooltip)
Vue.config.productionTip = false
Vue.prototype.$ajax = ajax
Vue.prototype.$api = api
Vue.prototype.$cookie = cookie
Vue.prototype.$com = common
Vue.prototype.$message = message
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
import Vue from 'vue'
import Router from 'vue-router'
import {routes} from './routes'
import Cookie from '@/util/local-cookie'
Vue.use(Router)
const config = {
routes,
}
const router = new Router(config)
// router.beforeEach((to, from, next) => {
// const token = Cookie.get('token')
// // 当前无token且不在login页面则推到登录页面
// if (to.path != '/login' && !token) {
// next('/login')
// } else {
// next()
// }
// })
export default router
const HomePage = () => import('@/views/home')
const LoginPage = () => import('@/views/login')
export const routes = [
{
path: '/',
name: 'main',
redirect: '/home',
},
{
path: '/home',
name: 'home',
meta: {
title: '首页',
},
component: HomePage,
},
{
path: '/login',
name: 'login',
component: LoginPage,
},
]
import axios from 'axios'
import qs from 'qs'
import api from './api'
import Store from '@/store'
import Cookie from '@/util/local-cookie'
import router from '@/router'
import {message} from 'ant-design-vue'
// 配置请求的根域名和超时时间
const Axios = axios.create({
baseURL: api.BASE_URL,
timeout: 15000,
})
const CancelToken = axios.CancelToken
let cancelRequest = null
// 根据报错的状态码进行错误处理
const errorHandler = (err) => {
const errStatus = (err.response && err.response.status) || (err.data && err.data.errcode)
if (errStatus) {
switch (errStatus) {
case 451:
// token过期则推到登录页面
message.error('token过期,请重新登录')
router.push({
name: 'login',
})
break
case 404:
message.error('网络请求不存在')
break
case 500:
const code = err.response.data && err.response.data.code
if (code == 911) {
// refresh token过期则重新获取token或refresh token并刷新页面
const params = {
grant_type: 'refresh_token',
client_id: 'house',
client_secret: 'house',
refresh_token: Cookie.get('refresh_token'),
}
request({
method: 'POST',
url: api.GET_TOKEN,
params,
contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
}).then(res => {
Cookie.set('token', res.access_token)
Cookie.set('refresh_token', res.refresh_token)
router.go(0)
})
} else if (code == 710) {
message.error(err.response.data.msg)
} else {
const resMsg = err.response.data && err.response.data.msg
console.error(resMsg)
message.error('500: 请求失败')
}
break
default:
message.error(err.response.data.message)
}
}else if (err.toString().indexOf('timeout') != -1) {
Message.error('请求超时')
} else if (err.toString().indexOf('Network Error') != -1) {
Message.error('网络连接中断')
}
}
Axios.interceptors.request.use(config => {
const token = Cookie.get('token') || Store.state.token
if (token) {
config.headers.Authorization = token
}
return config
}, error => {
return Promise.reject(error)
})
Axios.interceptors.response.use(response => {
return response.data
}, error => {
errorHandler(error)
return error
})
/**
* 请求
* @param {String} method [请求方法]
* @param {String} url [请求地址]
* @param {Object} params [请求参数]
* @param {String} contentType [请求头,默认为'application/json;charset=UTF-8']
* @param {Boolean} hideLoading [隐藏请求时的loading图,默认为false]
*/
const request = ({method, url, params, contentType = 'application/json;charset=UTF-8', hideLoading = false}) => {
if (!url || typeof(url) != 'string') {
throw new Error('接口URL不正确')
}
if (!params || typeof(params) == 'string' || typeof(params) == 'number') {
params = {}
}
let config = {
method,
url,
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': contentType,
},
cancelToken: new CancelToken((c) => {
cancelRequest = c
}),
}
if (method === 'GET') {
config = Object.assign(config, {params})
} else {
if (contentType.toLowerCase().indexOf('x-www-form-urlencoded') >= 0) {
config = Object.assign(config, {data: qs.stringify(params)})
} else {
config = Object.assign(config, {data: params})
}
}
if (!hideLoading) {
Store.commit('SET_LOADING', true)
}
return new Promise((resolve, reject) => {
Axios(config)
.then(res => {
resolve(res)
Store.commit('SET_LOADING', false)
}).catch(err => {
reject(err)
Store.commit('SET_LOADING', false)
})
})
}
export default {
/**
* 取消请求
* @param {String} txt [取消请求时需要显示在控制台的提示信息]
*/
cancel(txt = '取消请求') {
Store.commit('SET_LOADING', false)
if (typeof(cancelRequest) === 'function') {
return cancelRequest(txt)
}
},
get(args) {
return request({method: 'GET', ...args})
},
post(args) {
return request({method: 'POST', ...args})
},
put(args) {
return request({method: 'PUT', ...args})
},
delete(args) {
return request({method: 'DELETE', ...args})
},
all(...ajaxs) {
return Promise.all(ajaxs)
},
}
let BASE_URL = ''
switch (process.env.NODE_ENV) {
case 'sit': // sit环境下
BASE_URL = 'https://sit/api'
break
case 'uat': // uat环境下
BASE_URL = 'https://uat/api'
break
case 'production': // 生产环境下
BASE_URL = 'https://pro/api'
break
default: // 默认环境下(开发环境)
BASE_URL = 'http://localhost:8080'
break
};
export default {
BASE_URL,
GET_TOKEN: '/uaa/oauth/token', // 获取token
}
export default {
}
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import actions from './actions'
import mutations from './mutations'
Vue.use(Vuex)
const isDev = process.env.NODE_ENV === 'development'
export default new Vuex.Store({
strict: isDev,
state,
actions,
mutations,
})
export default {
SET_LOADING(state, data) {
state.showLoading = data
},
}
export default {
token: null,
showLoading: false,
}
/** 公共方法 */
export default {
/**
* 在深层数据结构中取值(为了替代类似 res && res.data && res.data.content这种写法)
* @param {Object} obj [必填-需要取值的目标对象(例:res)]
* @param {String} path [必填-数据结构路径(例:'data.content')]
* @param {Any} defaultValue [可选-如果取不到值则默认返回该值]
*/
confirm(obj, path, defaultValue = null) {
if (!obj || typeof(obj) != 'object' || !path || typeof(path) != 'string') return
const reducer = (accumulator, currentValue) =>
(accumulator && accumulator[currentValue]) ?
accumulator[currentValue] :
defaultValue
path = path.split('.')
return path.reduce(reducer, obj)
},
/**
* ----- 柯里化版本 (为了不再重复输入obj这个参数) -----
* 在深层数据结构中取值(为了替代类似 res && res.data && res.data.content这种写法)
* @param {Object} obj [必填-需要取值的目标对象(例:res)]
*/
confirm_currying(obj) {
if (!obj || typeof(obj) != 'object') return
return (path, defaultValue = null) => {
if (!path || typeof(path) != 'string') return
const reducer = (accumulator, currentValue) =>
(accumulator && accumulator[currentValue]) ?
accumulator[currentValue] :
defaultValue
path = path.split('.')
return path.reduce(reducer, obj)
}
},
/**
* 转换为金钱格式(千分位且保留两位小数)
* @param {Number | String} num [需转换的数字或字符串]
*/
toMoney(num) {
if (!num) {
return 0.00
}
num = this.toFloat(num).toFixed(2)
const arr = num.toString().split('.')
let int = (arr[0] || 0).toString(),
result = ''
while (int.length > 3) {
result = ',' + int.slice(-3) + result
int = int.slice(0, int.length - 3)
}
if (int) {
result = int + result
}
return `${result}.${arr[1]}`
},
/**
* 手机号码校验
* @param {String} num [需校验的手机号码]
*/
checkPhone(num) {
if (!num) return false
const filter = /^1[3-9][0-9]{9}$/
return filter.test(num)
},
/**
* 固定电话号码校验
* @param {String} num [需校验的固话]
*/
checkTel(num) {
if (!num) return false
const filter = /^(?:0[1-9][0-9]{1,2}-)?[2-8][0-9]{6,7}$/
return filter.test(num)
},
/**
* 身份证号码校验
* @param {String} num [需校验的身份证号码]
*/
checkID(num) {
if (!num) return false
const filter = /(^\d{15}$)|(^\d{17}([0-9]|X)$)/
return filter.test(num)
},
/**
* 数字校验(整数或者小数)
* @param {String} num [需校验的数字]
*/
checkNumber(num) {
if (!num && num != 0) return false
const filter = /^[0-9]+\.{0,1}[0-9]{0,2}$/
return filter.test(num)
},
/**
* 文本校验(只能为中文、英文、数字组合,不允许其他特殊符号)
* @param {String} txt [需校验的文本]
*/
checkContent(txt) {
const filter = /^[\u4E00-\u9FA5A-Za-z0-9]+$/
return filter.test(txt)
},
}
/* 用于判断electron状态下使用localstorage替换js-cookie */
import jscookie from 'js-cookie'
import localcookie from './local-cookie'
const isElectronApp = window.navigator.userAgent.indexOf('Electron') !== -1
export default isElectronApp ? localcookie : jscookie
export default {
get(key) {
if (!key) {
return null
}
return localStorage.getItem(key)
},
set(key, val) {
if (!key) {
return null
}
localStorage.setItem(key, val)
},
remove(key) {
if (!key) {
return null
}
localStorage.removeItem(key)
},
}
<template>
<div>
<h1>Home Page</h1>
<ExampleForm/>
<ExampleTable/>
</div>
</template>
<script>
import ExampleForm from '@/components/ActiveForm/example'
import ExampleTable from '@/components/ActiveTable/example'
export default {
name: 'HomePage',
components: {
ExampleForm,
ExampleTable,
}
}
</script>
<style>
</style>
<template>
<div id="login-container" :style="bgStyle">
<img class="logo" src="@/assets/images/logo.png" alt="logo">
<a-card class="login-box">
<h3 style="color: #40a9ff;">登录</h3>
<a-form :form="form">
<a-form-item>
<a-input placeholder="用户名">
<a-icon
slot="prefix"
type="user"
style="color:rgba(0,0,0,.25)"
/>
</a-input>
</a-form-item>
<a-form-item>
<a-input type="password" placeholder="密码">
<a-icon
slot="prefix"
type="lock"
style="color:rgba(0,0,0,.25)"
/>
</a-input>
</a-form-item>
<a-form-item>
<a-button @click="login" type="primary" block html-type="submit">
登录
</a-button>
</a-form-item>
</a-form>
<Loader msg="登录中..."/>
</a-card>
</div>
</template>
<script>
import bgImg from '@/assets/images/login-bg.png'
import Loader from '@/components/Loader/loader'
export default {
name: 'Login',
components: {
Loader,
},
data() {
return {
tabName: 'login',
form: this.$form.createForm(this),
bgStyle: {'background-image': 'url(' + bgImg +')'},
loginInfo: {},
}
},
created() {
},
methods: {
login() {
},
},
}
</script>
<style scoped>
#login-container {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
background-size: cover;
background-position: center;
background-repeat: no-repeat;
align-items: center;
justify-content: center;
}
.login-box {
width: 280px;
background: #ffffff;
border-radius: 5px;
}
.login-box input {
margin-top: 20px;
}
.login-box .ivu-form-item-content {
line-height: 0;
}
.btn-wrapper {
text-align: center;
margin-bottom: 0;
}
.btn-wrapper button {
width: 100%;
}
.logo {
width: 80px;
height: 80px;
margin-bottom: 30px;
/* border: 2px solid #fff;
border-radius: 50%; */
padding: 5px;
}
.type-wrapper {
font-size: 12px;
color: #c9c9c9;
margin-bottom: 10px;
}
.type-wrapper span {
cursor: pointer;
}
.type-wrapper span:hover {
color: #0076FF;
}
.type-wrapper span.active {
color: #0076FF;
}
.pwd-operate {
display: flex;
align-items: center;
justify-content: space-between;
padding-left: 1px;
margin-bottom: 10px;
}
</style>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment