Commit 69d84cfc authored by huanglu's avatar huanglu

feat: 优化模板

parent edac3b99
{
"types": ["feat", "fix", "docs", "style", "refactor", "perf", "test", "build", "ci", "chore", "revert"],
"scope": {
"required": false,
"allowed": ["*"],
"validate": false,
"multiple": false
},
"warnOnFail": false,
"maxSubjectLength": 100,
"subjectPattern": ".+",
"subjectPatternErrorMsg": "subject does not match subject pattern!",
"helpMessage": "",
"autoFix": false
}
\ No newline at end of file
const path = require('path') const path = require('path');
const pages = require('./util').multiPages()
const pkg = require('../package.json')
const resolve = (dir) => path.join(__dirname, '../', dir) const resolve = (dir) => {
return path.join(__dirname, '..', dir);
};
module.exports = { module.exports = {
devServer: { outputDir: 'mobile',
proxy: { proxy: {
'/api': { '/service-profile': {
target: 'http://localhost:3000', target: 'http://192.168.32.57:3000',
pathRewrite: { '^/api': '' }, changeOrigin: true,
}, },
}, },
port: 3000
},
publicPath: '/', publicPath: '/',
ouputDir: 'dist', alias: {
pages, // 配置这个,注意配置 jsconfig.json 文件,方便 vscode 能够跳进
'@': resolve('src'),
},
externals: { externals: {
}, },
alias: { skeletonRoutes: [
} '/', '/normal/about'
} ]
};
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
"baseUrl": ".", "baseUrl": ".",
"paths": { "paths": {
"@/*": ["src/*"], "@/*": ["src/*"],
"@pages/*": ["src/pages/*"]
} }
} }
} }
\ No newline at end of file
...@@ -13,11 +13,13 @@ ...@@ -13,11 +13,13 @@
"dev": "npm run serve:dev", "dev": "npm run serve:dev",
"stage": "npm run serve:stage", "stage": "npm run serve:stage",
"prod": "npm run serve:prod", "prod": "npm run serve:prod",
"lint": "vue-cli-service lint" "lint": "vue-cli-service lint",
"postinstall": "node scripts/skeleton.js"
}, },
"dependencies": { "dependencies": {
"axios": "^0.19.2", "axios": "^0.19.2",
"core-js": "^3.6.4", "core-js": "^3.6.4",
"vant": "^2.9.1",
"vue": "^2.6.11", "vue": "^2.6.11",
"vue-router": "^3.1.6", "vue-router": "^3.1.6",
"vuex": "^3.1.3" "vuex": "^3.1.3"
...@@ -33,16 +35,19 @@ ...@@ -33,16 +35,19 @@
"eslint": "^6.7.2", "eslint": "^6.7.2",
"eslint-plugin-import": "^2.20.2", "eslint-plugin-import": "^2.20.2",
"eslint-plugin-vue": "^6.2.2", "eslint-plugin-vue": "^6.2.2",
"less": "^3.0.4",
"less-loader": "^5.0.0",
"lint-staged": "^9.5.0", "lint-staged": "^9.5.0",
"style-resources-loader": "^1.3.3", "node-sass": "^4.14.1",
"vue-cli-plugin-style-resources-loader": "^0.1.4", "page-skeleton-webpack-plugin": "^0.10.12",
"postcss-px-to-viewport": "^1.1.1",
"sass": "^1.26.8",
"sass-loader": "^8.0.2",
"validate-commit-msg": "^2.14.0",
"vue-template-compiler": "^2.6.11", "vue-template-compiler": "^2.6.11",
"webpack-bundle-analyzer": "^3.6.1" "webpack-bundle-analyzer": "^3.6.1"
}, },
"gitHooks": { "gitHooks": {
"pre-commit": "lint-staged" "pre-commit": "lint-staged",
"commit-msg": "validate-commit-msg"
}, },
"lint-staged": { "lint-staged": {
"*.{js,jsx,vue}": [ "*.{js,jsx,vue}": [
......
...@@ -11,20 +11,8 @@ ...@@ -11,20 +11,8 @@
<noscript> <noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript> </noscript>
<div id="app"></div> <div id="app">
<script> <!-- shell -->
(function(doc, win) { </div>
var docEl = doc.documentElement,
resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
recalc = function() {
var clientWidth = docEl.clientWidth;
if (!clientWidth) return;
docEl.style.fontSize = window.screen.width / 10 + 'px';
};
if (!doc.addEventListener) return;
win.addEventListener(resizeEvt, recalc, false);
doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);
</script>
</body> </body>
</html> </html>
'use strict'
const merge = require('lodash/merge')
const webpack = require('webpack')
const optionsSchema = require('./config/optionsSchema.json')
const Server = require('./server')
const { addScriptTag, outputSkeletonScreen, snakeToCamel } = require('./util')
const { defaultOptions, staticPath } = require('./config/config')
const OptionsValidationError = require('./config/optionsValidationError')
const EVENT_LIST = process.env.NODE_ENV === 'production' ? ['watch-close', 'failed', 'done'] : ['watch-close', 'failed']
const PLUGIN_NAME = 'pageSkeletonWebpackPlugin'
function SkeletonPlugin(options = {}) {
const validationErrors = webpack.validateSchema(optionsSchema, options)
if (validationErrors.length) {
throw new OptionsValidationError(validationErrors)
}
this.options = merge({ staticPath }, defaultOptions, options)
this.server = null
this.originalHtml = ''
}
SkeletonPlugin.prototype.createServer = function () { // eslint-disable-line func-names
if (!this.server) {
const server = this.server = new Server(this.options) // eslint-disable-line no-multi-assign
server.listen().catch(err => server.log.warn(err))
}
}
SkeletonPlugin.prototype.insertScriptToClient = function (htmlPluginData) { // eslint-disable-line func-names
// at develop phase, insert the interface code
if (process.env.NODE_ENV !== 'production') {
const { port } = this.options
const clientEntry = `http://localhost:${port}/${staticPath}/index.bundle.js`
const oldHtml = htmlPluginData.html
htmlPluginData.html = addScriptTag(oldHtml, clientEntry, port)
}
}
SkeletonPlugin.prototype.outputSkeletonScreen = async function () { // eslint-disable-line func-names
try {
await outputSkeletonScreen(this.originalHtml, this.options, this.server.log.info)
} catch (err) {
this.server.log.warn(err.toString())
}
}
SkeletonPlugin.prototype.apply = function (compiler) { // eslint-disable-line func-names
if (compiler.hooks) {
compiler.hooks.entryOption.tap(PLUGIN_NAME, () => {
this.createServer()
})
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.htmlWebpackPluginBeforeHtmlProcessing.tapAsync(PLUGIN_NAME, (htmlPluginData, callback) => {
this.insertScriptToClient(htmlPluginData)
callback(null, htmlPluginData)
})
compilation.hooks.htmlWebpackPluginAfterHtmlProcessing.tapAsync(PLUGIN_NAME, (htmlPluginData, callback) => {
this.originalHtml = htmlPluginData.html
callback(null, htmlPluginData)
})
})
compiler.hooks.afterEmit.tap(PLUGIN_NAME, async () => {
await this.outputSkeletonScreen()
})
EVENT_LIST.forEach((event) => {
compiler.hooks[snakeToCamel(event)].tap(PLUGIN_NAME, () => {
if (this.server) {
this.server.close()
}
})
})
} else {
compiler.plugin('entry-option', () => {
this.createServer()
})
compiler.plugin('compilation', (compilation) => {
compilation.plugin('html-webpack-plugin-before-html-processing', (htmlPluginData, callback) => {
this.insertScriptToClient(htmlPluginData)
callback(null, htmlPluginData)
})
compilation.plugin('html-webpack-plugin-after-html-processing', (htmlPluginData, callback) => {
this.originalHtml = htmlPluginData.html
callback(null, htmlPluginData)
})
})
compiler.plugin('after-emit', async (compilation, done) => {
await this.outputSkeletonScreen()
done()
})
EVENT_LIST.forEach((event) => {
compiler.plugin(event, () => {
if (this.server) {
this.server.close()
}
})
})
}
}
module.exports = SkeletonPlugin
const fs = require('fs')
const path = require('path')
const changeSkeleton = () => {
const txt = fs.readFileSync(path.join(__dirname, './skeleton-plugin.txt'), {
encoding: 'utf8'
})
const targetFile = path.join(__dirname, '..', 'node_modules/page-skeleton-webpack-plugin/src/skeletonPlugin.js')
try {
fs.writeFileSync(targetFile, txt, {
encoding: 'utf8'
})
} catch (error) {
console.log('error: ', error)
}
}
console.log('changeSkeleton')
changeSkeleton()
\ No newline at end of file
<template>
<div id="app">
<router-view />
</div>
</template>
<script>
export default {
watch: {
$route(N) {
if (!this._title) {
this._title = window.document.title;
}
if (N.meta && N.meta.title) {
window.document.title = N.meta.title;
this.$nativeTitle(N.meta.title);
} else {
window.document.title = this._title;
this.$nativeTitle(this._title);
this._title = null;
}
}
},
beforeDestroy() {}
};
</script>
<style lang="scss">
.wrap {
color: $geekColor;
}
body {
width: 100vw;
}
#app {
width: 100vw;
}
img {
max-width: 100vw;
}
</style>
import { post } from '@/utils/request';
// 极客数学帮(家长APP)/极客资料/添加预习题目答题记录
export const addPrepareQuestionStudyLog = (params) => post('/service-profile/app/geekMaterial/addPrepareQuestionStudyLog', params);
import videoPlay from './video_play.png'
import videoBg from './video_bg.png'
import nocontent from './nocontent.png'
export {
videoPlay,
videoBg,
nocontent
}
\ No newline at end of file
body,ol,ul,h1,h2,h3,h4,h5,h6,p,th,td,dl,dd,form,
fieldset,legend,input,textarea, select {
margin: 0;
padding: 0;
}
p, span, div, body {
word-break:break-all;
-webkit-overflow-scrolling: touch;
}
\ No newline at end of file
@import './clear.scss';
.bordered {
border-top: solid 1px black;
}
@mixin ellipsis($num: 1) {
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: $num;
-webkit-box-orient: vertical;
}
@mixin flexLayout($direction: row, $alignItems: center, $justc: flex-start) {
display: flex;
flex-direction: $direction;
justify-content: $justc;
align-items: $alignItems;
}
$good: 'red';
$geekColor: yellow;
import Notify from './notify-message'
function install(Vue) {
const NotifyConstructor = Vue.extend(Notify)
const errNotify = new NotifyConstructor({
duration: 500,
})
const errorDiv = document.createElement('div')
errorDiv.setAttribute('id', 'error_wrap');
document.body.appendChild(errorDiv)
errNotify.$mount(errorDiv)
const errorNotify = {
show(message, duration) {
errNotify.showNotify(message, duration)
},
hidden() {
errNotify.hiddenNotify()
}
}
Vue.prototype.$errorNotify = errorNotify
}
export default install
\ No newline at end of file
<template>
<transition name="fade" class="">
<div v-if="show">
<div class="cm-notify-message">
<img class="icon" :src="errorImg">
<span class="content">{{ message || '' }}</span>
<img class="icon" :src="closeImg" @click="hiddenNotify">
</div>
</div>
</transition>
</template>
<script>
import errorImg from './images/error.png'
import closeImg from './images/close.png'
export default {
props: {
duration: {
type: Number,
default: 1000
}
},
data() {
return {
errorImg,
closeImg,
show: false,
message: ''
};
},
created() {
},
methods: {
showNotify(message, duration) {
this.show = true
this.message = message
if (this.duration <= 0) {
return
}
if (this.timer) {
clearTimeout(this.timer)
}
this.timer = setTimeout(() => {
this.show = false
}, duration || this.duration);
},
hiddenNotify() {
this.show = false
}
},
mounted() {
}
}
</script>
<style lang='scss'>
.cm-notify-message {
position: fixed;
top: 0;left: 0;right: 0;
box-sizing: border-box;
display: flex;
flex-flow: row;
align-items: center;
background: #FFF1F0;
border: 1px solid #FFA39E;
padding: 8px;
width: 100vw;
font-size:12px;
font-family:MicrosoftYaHei;
color:rgba(0,0,0,0.65);
.content {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
word-break: break-all;
-webkit-box-orient: vertical;
margin: 0 10px;
}
.icon {
width: 15px;
height: 15px;
}
}
.fade-enter-active, .fade-leave-active {
transition: all 0.25s;
position: fixed;
top: 0; left: 0; right: 0;
}
.fade-enter, .fade-leave-to {
transform: translateY(-60px);
}
</style>
\ No newline at end of file
import HelloWorld from './hello-world' import ErrorNotify from './error-nofity'
import VideoItem from './video-item'
export { export {
HelloWorld ErrorNotify,
VideoItem
} }
<template>
<div class="cm-video-item">
<div class="video-wrap">
<img :src="img" />
<img :src="videoPlay" class="thumbImg" />
<span class="status" :class="status ? 'status-done' : ''">{{ status | playStatus }}</span>
</div>
<span>{{title}}</span>
</div>
</template>
<script>
import { videoPlay } from "@/assets/images";
export default {
data() {
return {
videoPlay
};
},
filters: {
playStatus(status) {
return status ? '已学习' : '未学习'
}
},
props: {
img: { type: String, default: '' },
title: { type: String, default: '' },
status: { type: Boolean, default: false }
},
methods: {},
mounted() {}
};
</script>
<style lang="scss">
.cm-video-item {
@include flexLayout(column);
box-sizing: border-box;
font-size: 12px;
font-family: PingFangSC-Regular, PingFang SC;
font-weight: 400;
color: rgba(72, 76, 79, 1);
position: relative;
overflow: hidden;
img {
height: 90px;
object-fit: cover;
width: 100%;
}
span {
@include ellipsis;
}
.video-wrap {
flex: 1;
position: relative;
.thumbImg {
position: absolute;
top: 50%;
right: 50%;
width: 50px;
height: 50px;
transform: translateX(50%) translateY(-50%);
}
.status {
position: absolute;
top: 0; right: 0;
padding: 3px 8px;
font-size: 12px;
color: #FE5A5A;
background:rgba(0,0,0,0.6);
border-bottom-left-radius: 6px;
&-done {
color: #64B352;
}
}
}
}
</style>
\ No newline at end of file
.border(@width: 1px, @color: #f5f5f5) {
border: @width solid @color;
}
//
.toRpx(@name: width, @value: 20px) {
@{name}: @value / 375 * 100vw;
}
\ No newline at end of file
@good: 'red';
@geekColor: '#f8f8f8';
<template> <template>
<div id="app"> <div>
<keep-alive> <keep-alive>
<router-view v-if="$route.meta.keepAlive"/> <router-view v-if="$route.meta.keepAlive"/>
</keep-alive> </keep-alive>
<router-view v-if="!$route.meta.keepAlive"/> <router-view v-if="!$route.meta.keepAlive"/>
</div> </div>
</template> </template>
<script> <script>
export default { export default {
mounted() { data() {
return {};
}, },
methods: { methods: {
}, },
}; watch: {
},
mounted() {
},
beforeDestroy() {
}
}
</script> </script>
<style>
<style lang="less" scoped>
</style> </style>
\ No newline at end of file
import Vue from 'vue'; import Vue from 'vue';
import router from '@/router';
import store from '@/store';
import { nativeBrige } from '@/plugins';
import ErrorNotify from '@/components/error-nofity'
import {
Tag, Button, Toast, Loading
} from 'vant';
import App from './App.vue'; import App from './App.vue';
import router from './router';
import store from './store';
Vue.config.productionTip = false; Vue.config.productionTip = false;
Vue.use(Tag);
console.log([1,2,3].includes(12)) Vue.use(Button);
Vue.use(Toast);
Vue.use(Loading);
Vue.use(nativeBrige);
Vue.use(ErrorNotify)
new Vue({ new Vue({
router, router,
......
import { get, post } from '@/utils/request';
export const login = (username, password) => post('/login', { username, password });
export const userinfo = (params) => get('/userinfo', params);
<template>
<span> 页面组件 </span>
</template>
<script>
export default {
components: {},
data() {
return {};
},
methods: {
},
mounted() {
}
}
</script>
<style>
</style>
\ No newline at end of file
import Vue from "vue";
import VueRouter from "vue-router";
import globalRoutes from "@/router";
const Index = () => import("../views/Index");
Vue.use(VueRouter);
// 单入口路由配置
const routes = [
{
path: "/",
name: "index",
component: Index
}
];
const router = new VueRouter({
mode: "hash",
base: process.env.BASE_URL,
routes: [...globalRoutes, ...routes]
});
export default router;
<template>
<div class="about">
<h1>This is an Index page</h1>
</div>
</template>
/* eslint-disable import/prefer-default-export */
import nativeBrige from './nativebrige';
export {
nativeBrige,
}
\ No newline at end of file
const isiOS = () => {
const u = navigator.userAgent;
const iOs = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
return iOs;
};
const isAndroid = () => {
const u = navigator.userAgent;
const android = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
return android;
};
const postMessage = (data) => {
if (isAndroid()) {
window.ReactNativeWebView
&& window.ReactNativeWebView.onMessage(JSON.stringify(data));
} else {
window.ReactNativeWebView
&& window.ReactNativeWebView.postMessage(JSON.stringify(data));
}
};
if (isiOS() || isAndroid()) {
const debugLog = console.log
// eslint-disable-next-line func-names
console.log = function (...args) {
postMessage({
type: 'log',
data: args
})
debugLog(args)
}
}
function install(Vue) {
console.log('plugins: ', Vue)
const GEEK_NATVIE_NAME = 'GEEK_NATVIE_NAME';
// eslint-disable-next-line camelcase
const event_bus = new Vue();
// eslint-disable-next-line func-names
window.$geek_excuteJS = function (args) {
try {
const params = JSON.parse(args);
event_bus.$emit(GEEK_NATVIE_NAME, params);
} catch (error) {
event_bus.$emit(GEEK_NATVIE_NAME, args);
}
};
const nativeMixin = {
methods: {
listenNativeMessage(arg) {
const { method, data } = arg;
if (method) {
this[method] && this[method](data);
}
},
$nativeTitle(title) {
const message = {
type: 'title',
data: title,
};
postMessage(message);
},
$shareImg(base64Img, timeline = false) {
const message = {
type: timeline ? 'shareTimeline' : 'share',
data: {
type: 'img',
img: base64Img,
},
};
postMessage(message);
},
$shareText(txt, timeline = false) {
const message = {
type: timeline ? 'shareTimeline' : 'share',
data: {
type: 'text',
description: txt,
},
};
postMessage(message);
},
$shareNews({ title, url, description }, timeline = false) {
const message = {
type: timeline ? 'shareTimeline' : 'share',
data: {
type: 'news',
description,
webpageUrl: url,
title,
},
};
postMessage(message);
},
$playVieo(url) {
const message = {
type: 'video',
data: {
url,
},
};
postMessage(message);
},
$postMessage(message) {
postMessage(message);
},
},
created() {
event_bus.$on(GEEK_NATVIE_NAME, this.listenNativeMessage);
},
beforeDestroy() {
event_bus.$off('GEEK_NATVIE_NAME', this.listenNativeMessage);
},
};
Vue.mixin(nativeMixin);
}
export default install;
const Cart = () => import('@/views/cart')
// 单入口路由配置
const routes = [
{
path: "/cart",
name: "Cart",
component: Cart
}
];
export default routes;
import Vue from 'vue';
import VueRouter from 'vue-router';
import NormalLayout from '@/layout/normal-layout'
import utils from '@/utils';
const Home = () => import('@/views/home')
const About = () => import('@/views/about')
Vue.use(VueRouter);
// 单入口路由配置
const routes = [
{
path: '/normal',
component: NormalLayout,
children: [
{
path: 'about',
component: About,
}
]
},
{
path: '/home',
component: Home,
meta: {
title: 'home'
},
},
{
path: '/',
component: () => import('@/views/index')
}
];
export {
routes
}
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes,
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition
}
return { x: 0, y: 0 }
}
});
router.beforeEach((to, from , next) => {
// 进入页面前, 如果
if (to.query) {
const token = to.query.token || ''
token && utils.storage.setStorage('token', token)
}
next()
})
export default router;
...@@ -13,6 +13,7 @@ reqiureContext.keys().forEach((key) => { ...@@ -13,6 +13,7 @@ reqiureContext.keys().forEach((key) => {
}); });
export default new Vuex.Store({ export default new Vuex.Store({
namespaced: true,
modules: { modules: {
...modules, ...modules,
}, },
......
...@@ -16,6 +16,7 @@ const getters = { ...@@ -16,6 +16,7 @@ const getters = {
}; };
export default { export default {
namespaced: true,
state, state,
getters, getters,
mutations, mutations,
......
...@@ -3,7 +3,7 @@ const state = { ...@@ -3,7 +3,7 @@ const state = {
}; };
const actions = { const actions = {
addCart({ commit, state }, cart) { addCart({ commit }, cart) {
setTimeout(() => { setTimeout(() => {
commit('addCart', cart); commit('addCart', cart);
}, 1000); }, 1000);
...@@ -36,6 +36,7 @@ const mutations = { ...@@ -36,6 +36,7 @@ const mutations = {
}; };
export default { export default {
namespaced: true,
state, state,
mutations, mutations,
actions, actions,
......
import { Toast } from 'vant';
import * as storage from './storage'
const isiOS = () => {
const u = navigator.userAgent
const iOs = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
return iOs;
}
const isAndroid = () => {
const u = navigator.userAgent
const android = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
return android
}
function postMessage({
type = 'data',
data = ''
}) {
if (typeof data !== 'string') {
data = JSON.stringify(data)
}
const message = {
data,
type
}
if (isAndroid()) {
window.ReactNativeWebView && window.ReactNativeWebView.onMessage(JSON.stringify(message))
} else {
window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify(message))
}
}
/**
* @type image / text/ file
* @data i
* mg => base64 ,
* text => string ,
* news: { title: string, webpageUrl: url, description: string }
*/
const share = (data) => {
postMessage({
type: 'share',
data
})
};
const insertTxtInHtml = (txt, html) => {
if (/^<\w+>.*/g.test(html)) {
const index = html.search(/>/)
return html.slice(0,index + 1) + txt + html.slice(index + 1)
}
return txt + html
}
const showLoading = (message) => {
Toast.loading({
message,
duration: 0
})
}
const hideLoading = () => {
Toast.clear()
}
const showSuccess = (message) => {
Toast.success(message)
}
const showWarn = (message) => {
Toast(message)
}
const showFail = (message) => {
Toast.fail(message)
}
export default {
share,
postMessage,
storage,
isiOS,
isAndroid,
insertTxtInHtml,
showLoading,
hideLoading,
showSuccess,
showWarn,
showFail
};
import axios from 'axios'; import axios from 'axios';
import utils from '.';
const http = axios.create({ const http = axios.create({
baseUrl: process.env.VUE_APP_API_HOST || process.env.BASE_URL baseUrl: process.env.VUE_APP_API_HOST || process.env.BASE_URL,
}) });
http.defaults.timeout = 10000; http.defaults.timeout = 10000;
...@@ -10,26 +11,39 @@ http.defaults.timeout = 10000; ...@@ -10,26 +11,39 @@ http.defaults.timeout = 10000;
http.interceptors.response.use( http.interceptors.response.use(
(response) => { (response) => {
if (response.status >= 200 && response.status <= 299) { if (response.status >= 200 && response.status <= 299) {
// 配置响应 const { data } = response;
return Promise.resolve(response.data); if (data.code === 0) {
return Promise.resolve([data.data, null]);
} }
// TODO: 其他配置 return Promise.resolve([null, { code: data.code, msg: data.msg || '' }]);
return Promise.reject(response.data); }
return Promise.resolve([
null,
{ code: response.status, msg: '请求失败...' },
]);
}, },
(error) => { (error) => {
if (error.response.status) { if (error.response && error.response.status) {
return Promise.reject('请求失败'); return Promise.resolve([
null,
{ code: error.response.status, msg: '请求失败...' },
]);
}
return Promise.resolve([null, { code: 1000, msg: '请求失败...' }]);
} }
},
); );
http.interceptors.request.use( http.interceptors.request.use(
(config) => { (config) => {
// 设置token 或者 全局参数, headers等 // 设置token 或者 全局参数, headers等
config.headers = { 'Content-Type': 'application/json' }; config.headers = { 'Content-Type': 'application/json' };
const token = utils.storage.getStorage('token')
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config; return config;
}, },
(err) => Promise.reject(err), (err) => Promise.reject(err)
); );
/** /**
......
/*
* @Author: jiangang
* @Date: 2018-09-06 17:29:35
* @Last Modified by: jiangang
* @Last Modified time: 2018-09-06 17:30:02
*/
/**
* 设置本地缓存
* @param {string} key
* @param {any} val
*/
export function setStorage(key, val) {
localStorage.setItem(key, JSON.stringify(val))
}
/**
* 获取本地缓存
* @param {string} key
*/
export function getStorage(key) {
const val = localStorage.getItem(key)
return val === 'undefined' ? '' : JSON.parse(val)
}
/**
* 移除某一项缓存
* @param {string} key
*/
export function removeStorage(key) {
localStorage.removeItem(key)
}
/**
* 清除所有缓存
*/
export function clearStorage() {
localStorage.clear()
}
/**
* 设置本地临时缓存
* @param {string} key
* @param {any} val
*/
export function setSession(key, val) {
sessionStorage.setItem(key, JSON.stringify(val))
}
/**
* 获取本地临时缓存
* @param {string} key
*/
export function getSession(key) {
const val = sessionStorage.getItem(key)
return val === 'undefined' ? '' : JSON.parse(val)
}
/**
* 移除某一项临时缓存
* @param {string} key
*/
export function removeSession(key) {
sessionStorage.removeItem(key)
}
/**
* 清除所有临时缓存
*/
export function clearSession() {
sessionStorage.clear()
}
<template> <template>
<div>this si cart page</div> <div>sssss
<p> net : {{ mData }} </p>
<p> net : {{ mData }} </p>
<p> net : {{ mData }} </p>
<p> net : {{ mData }} </p>
<p> net : {{ mData }} </p>
</div>
</template> </template>
<script> <script>
export default { export default {
components: {}, components: {},
data() { data() {
return {}; return {
mData: '',
};
}, },
methods: { methods: {
}, },
mounted() { mounted() {
setTimeout(() => {
this.mData = new Date().getTime()
}, 1000)
} }
} }
</script> </script>
......
<template>
<div>this is home page
<van-button type="primary" @click="showNotify">notify</van-button>
<van-button type="primary" @click="showNotify">notify</van-button>
<van-button type="primary" @click="showNotify">notify</van-button>
<van-button type="primary" @click="showNotify">notify</van-button>
</div>
</template>
<script>
export default {
components: {
},
data() {
return {};
},
methods: {
showNotify() {
this.$errorNotify.show('sfafaf爱国发几个发几个发件方轧空广发卡价格法结构发几个房间爱广发卡价格法就开个房间爱干发巾开关啊啊发发发啊发发发发阀加工费', 3000)
}
}
}
</script>
<style>
</style>
\ No newline at end of file
<template> <template>
<span>全局组件</span> <p> mobile - html </p>
</template> </template>
<script> <script>
export default { export default {
......
<template>
<div>this is setting page</div>
</template>
<script>
export default {
components: {},
data() {
return {};
},
methods: {
},
mounted() {
}
}
</script>
<style>
</style>
\ No newline at end of file
// vue.config.js // vue.config.js
const { SkeletonPlugin } = require('page-skeleton-webpack-plugin')
const path = require('path'); const path = require("path");
const mock = require('./mock'); const mock = require('./mock');
const config = require('./config'); const config = require('./config');
const setAlias = (cfg) => { const resolve = (dir) => path.join(__dirname, dir);
Object.keys(config.alias).forEach((ala) => {
cfg.resolve.alias.set(ala, config.alias[ala]);
});
};
const setExternals = (cfg) => { console.log('skeletonRoutes : ', config.skeletonRoutes)
if (config.externals) {
cfg.externals(config.externals);
}
};
module.exports = { module.exports = {
configureWebpack: (wpConfig) => {
const plugins = [];
wpConfig.plugins = [...wpConfig.plugins, ...plugins,
new SkeletonPlugin({
staticDir: resolve(config.outputDir || 'dist'),
pathname: resolve('skeleton-pages'),
routes: [...config.skeletonRoutes]
})];
},
chainWebpack: (config) => {
if (process.env.NODE_ENV !== 'development') {
config.plugin('html').tap((opts) => {
opts[0].minify.removeComments = false
return opts
})
}
},
css: {
loaderOptions: {
postcss: {
plugins: [
// eslint-disable-next-line global-require
require('postcss-px-to-viewport')({
unitToConvert: 'px',
viewportWidth: 375,
viewportHeight: 667,
unitPrecision: 3,
propList: ['*'],
viewportUnit: 'vw',
fontViewportUnit: 'vw',
selectorBlaskList: ['.vant-'],
mediaQuery: false,
minPixelValue: 1,
replace: true,
exclude: [],
landscape: false,
landscapeUnit: 'vw',
landscapeWidth: 1134,
}),
],
},
sass: {
prependData: `
@import "@/assets/styles/common.scss";
@import "@/assets/styles/variable.scss";
`,
},
},
},
publicPath: config.publicPath || '/', publicPath: config.publicPath || '/',
lintOnSave: true, lintOnSave: true,
pages: config.pages, pages: config.pages,
outputDir: config.ouputDir || 'dist', outputDir: config.outputDir,
chainWebpack: (cfg) => {
setAlias(cfg);
setExternals(cfg);
},
devServer: { devServer: {
proxy: config.proxy || {},
port: 8080, port: 8080,
open: true, open: true,
hot: true, hot: true,
overlay: { overlay: {
warnings: false, warnings: false,
errors: true errors: true,
}, },
...config.devServer,
before(app) { before(app) {
Object.keys(mock).forEach((key) => { Object.keys(mock).forEach((key) => {
const mockValue = mock[key]; const mockValue = mock[key];
...@@ -46,15 +83,6 @@ module.exports = { ...@@ -46,15 +83,6 @@ module.exports = {
app.get(key.replace('GET', '').trim(), result); app.get(key.replace('GET', '').trim(), result);
} }
}); });
}
}, },
pluginOptions: {
'style-resources-loader': {
preProcessor: 'less',
patterns: [
path.resolve(__dirname, 'src/global/variable.less'),
path.resolve(__dirname, 'src/global/common.less')
] // 引入全局样式变量
}
}, },
}; };
This diff is collapsed.
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