Use Vue family bucket to develop mobile end page.
Bowen installed by default node.js.
github link
A. Preparations
- Installation vue
npm install vue
- Installation scaffolding vue-cli
npm install -g @vue/cli
- Creating webpack project
vue init webpack my-app
- run
cd my-app
npm run dev
Follow the prompts, opened in a browser http: // localhost: 8082 /, the effect is as follows:
- Installation state management vuex
npm install vuex --save-dev
- The directory structure
initial project directory as follows:
So far, the preparatory work is ready, the next will be the overall project design.
II. Project Design
1. Project catalog design
- In the
assets
directory is createdimages
,js
,css
folders.images
Folder, create aindex
folder to hold Home picture ( modular, so that the project structure at a glance ).
- In
src
Creating directorypages
directory users to store different functions pages.- And then in the
pages
creation directoryindex
Home directory.
- In the
index
creation directoryindex.vue
master file.
- And then in the
- modify
router
- modify
index.js
import Vue from 'vue' import Router from 'vue-router' import Index from '@/pages/index' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'Index', component: Index } ] })
- Browser effect
- modify
Delete
components
files in the directory, the directory as the page components folder is created in this directoryindex
folder storeindex
Home components.
- In
pages/index/index.vue
introducing header assembly
<template>
<div class="index-wrap">
<comHeader />
你好,首页
</div>
</template>
<script>
import header from '@/components/index/header'
export default {
data() {
return {
}
},
components: {
comHeader: header
}
}
</script>
<style scoped>
</style>
At this point, the entire structure of the project has been re-designed, let's introduction rem.js
and less
to allow us to develop more comfortable.
2. Move terminal adapter and less compilation, allowing developers to become happy.
- Mobile terminal adapter
rem
inassets/js
to create a foldercommon
in folders public js, and then create a file js rem fit in common folder. Andmain.js
the introduction of.
// rem.js
;(function (designWidth, maxWidth) {
var doc = document,
win = window;
var docEl = doc.documentElement;
var tid;
var rootItem, rootStyle;
function refreshRem() {
var width = docEl.getBoundingClientRect().width;
if (!maxWidth) {
maxWidth = 540;
}
;
if (width > maxWidth) {
width = maxWidth;
}
//与淘宝做法不同,直接采用简单的rem换算方法1rem=100px
var rem = width * 100 / designWidth;
//兼容UC开始
rootStyle = "html{font-size:" + rem + 'px !important}';
rootItem = document.getElementById('rootsize') || document.createElement("style");
if (!document.getElementById('rootsize')) {
document.getElementsByTagName("head")[0].appendChild(rootItem);
rootItem.id = 'rootsize';
}
if (rootItem.styleSheet) {
rootItem.styleSheet.disabled || (rootItem.styleSheet.cssText = rootStyle)
} else {
try {
rootItem.innerHTML = rootStyle
} catch (f) {
rootItem.innerText = rootStyle
}
}
//兼容UC结束
docEl.style.fontSize = rem + "px";
};
refreshRem();
win.addEventListener("resize", function () {
clearTimeout(tid); //防止执行两次
tid = setTimeout(refreshRem, 300);
}, false);
win.addEventListener("pageshow", function (e) {
if (e.persisted) { // 浏览器后退的时候重新计算
clearTimeout(tid);
tid = setTimeout(refreshRem, 300);
}
}, false);
if (doc.readyState === "complete") {
doc.body.style.fontSize = "16px";
} else {
doc.addEventListener("DOMContentLoaded", function (e) {
doc.body.style.fontSize = "16px";
}, false);
}
})(360, 750); // 360为设计图的尺寸,请按照实际设计图修改
// main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import '@/assets/js/common/rem.js' // 引入rem.js
Vue.config.productionTip = false
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
Thus, rem adaptation has been completed, when the writing style can be performed directly (FIG design size / 100) rem, for example, to design the elements as 200px height, then compared with rem height: 2rem
;
- less compilation, when writing style, in order to develop efficient, we use less compilation.
// 安装less和依赖
npm install less less-loader style-loader --save-dev
For example to header.vue
<template>
<div class="header-wrap">
我是头头头
<div class="title">
title
</div>
</div>
</template>
<script>
</script>
<style scoped lang="less">
.header-wrap{
height: 1rem;
background-color: #252627;
.title{
color: #fff;
height: .5rem;
}
}
</style>
At this point we can begin to develop a page.
3. State Managementstore
- installation
vuex
npm install vuex --save
- Create a directory structure store, as store principle hope you learn to master their own.
- index.js
/** * 组装模块并导出 store */ import Vue from 'vue' import Vuex from 'vuex' import game from './modules/game' import * as actions from './actions' import mutations from './mutations' import getters from './getters' Vue.use(Vuex) const debug = process.env.NODE_ENV !== 'production' const state = { userInfo:{} } export default new Vuex.Store({ state: state, actions: actions, mutations: mutations, getters:getters, modules: { game, }, strict: debug })
- Use store
this.$store.dispatch('getData', response.data.data)
4. Data Request axios
- In
src
the directory wear autils
directory for storing tools js. Inutils
creating therequest.js
toaxios
request package.
import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import config from '../../config/config'
import toast from './toast'
import store from '@/store'
const service = axios.create({
baseURL: 'www.baidu.com',
timeout:0// request timeout
})
service.interceptors.request.use(
requestConfig => {
let data = {
// 公共请求参数
};
requestConfig.data = Object.assign({}, requestConfig.data, data)
return requestConfig
},
error => {
Promise.reject(error)
}
)
// response interceptor
service.interceptors.response.use(response => {
const res = response.data
if (res.errno === 501) {
MessageBox.alert('系统未登录,请重新登录', '错误', {
confirmButtonText: '确定',
type: 'error'
}).then(() => {
})
return Promise.reject('error')
} else if (res.errno === 502) {
toast.showToast('系统内部错误,请联系管理员维护',1200,'error')
return Promise.reject('error')
} else if (res.errno === 503) {
toast.showToast('请求业务目前未支持',1200,'error')
return Promise.reject('error')
} else if (res.errno === 504) {
toast.showToast('更新数据已经失效,请刷新页面重新操作',1200,'error')
return Promise.reject('error')
} else if (res.errno === 505) {
toast.showToast('更新失败,请再尝试一次',1200,'error')
return Promise.reject('error')
} else if (res.errno === 506) {
toast.showToast('没有操作权限,请联系管理员授权',1200,'error')
return Promise.reject('error')
} else {
return response
}
}, error => {
toast.showToast('登录连接超时',5 * 1000,'error')
return Promise.reject(error)
})
export default service
- In
src
under a common directoryapi
folder and create components index.js
import request from '../utils/request'
/**
* @method getUserInfo 获取用户信息
* @param query {Object}
*/
export function getUserInfo(query){
return request({
url: 'user/info',
method: 'post',
data: query
})
}
- In
index.vue
call
<template>
<div class="index-wrap">
<comHeader />
你好,首页
</div>
</template>
<script>
import header from '@/components/index/header'
import { getUserInfo } from '@/api/index.js' // 引入
export default {
data() {
return {
}
},
components: {
comHeader: header
},
methods: {
getInfo(){
getUserInfo() //业务逻辑
.then(res => {
// do something
})
.catch(response => {})
}
},
created() {
this.getInfo(); //调用
}
}
</script>
<style scoped lang="less">
</style>
III. Compile release
1. compiled dist
npm run build
//在根目录下生成dis文件夹,可以将此文件夹放到oss上以供不同浏览器浏览。
to sum up
- In the course of development projects to consider a modular project.
- As far as possible the code specifications, specific code specifications are available at my other blog refer to the following:
- The actual project specific issues in the private letter I can jointly solve common learning. You can read this post and feel pleasure .