ue 2 指令是特殊的 HTML 屬性,用于將數(shù)據(jù)綁定到 DOM 元素或執(zhí)行其他操作。它們以 v- 前綴開頭,后面跟著指令名稱。
內(nèi)置指令
Vue 2 提供了許多內(nèi)置指令,用于執(zhí)行常見任務(wù),例如:
v-model: 將數(shù)據(jù)綁定到輸入元素的值
v-text: 將數(shù)據(jù)綁定到元素的文本內(nèi)容
v-html: 將數(shù)據(jù)綁定到元素的 HTML 內(nèi)容
v-if: 根據(jù)條件顯示或隱藏元素
v-for: 循環(huán)遍歷數(shù)組并渲染元素
v-on: 在元素上添加事件偵聽器
v-bind: 動(dòng)態(tài)綁定元素屬性
v-class: 動(dòng)態(tài)添加或刪除 CSS 類
自定義指令
您還可以創(chuàng)建自己的自定義指令以擴(kuò)展 Vue 的功能。自定義指令由 JavaScript 對(duì)象組成,該對(duì)象定義指令的鉤子函數(shù)。
指令鉤子函數(shù)包括:
bind: 指令首次綁定到元素時(shí)調(diào)用
inserted: 指令綁定的元素插入 DOM 時(shí)調(diào)用
update: 指令綁定的元素或其屬性更新時(shí)調(diào)用
componentUpdated: 指令所在的組件更新時(shí)調(diào)用
unbind: 指令與元素解綁時(shí)調(diào)用
有關(guān) Vue 2 指令的更多信息,請(qǐng)參閱以下資源:
Vue 2 指令文檔 [移除了無效網(wǎng)址]
創(chuàng)建自定義指令 [移除了無效網(wǎng)址]
以下是一些 Vue 2 指令的示例:
v-model 示例
HTML
于parseHTML函數(shù)代碼實(shí)在過于龐大,我這里就不一次性貼出源代碼了,大家可以前往(https://github.com/vuejs/vue/blob/dev/src/compiler/parser/html-parser.js)查看源代碼。
我們來總結(jié)一下該函數(shù)的主要功能:
1、匹配標(biāo)簽的 "<" 字符
匹配的標(biāo)簽名稱不能是:script、style、textarea
有如下情況:
1、注釋標(biāo)簽 /^<!\--/
2、條件注釋 /^<!\[/
3、html文檔頭部 /^<!DOCTYPE [^>]+>/i
4、標(biāo)簽結(jié)束 /^<\/ 開頭
5、標(biāo)簽開始 /^</ 開頭
然后開始匹配標(biāo)簽的屬性包括w3的標(biāo)準(zhǔn)屬性(id、class)或者自定義的任何屬性,以及vue的指令(v-、:、@)等,直到匹配到 "/>" 標(biāo)簽的結(jié)尾。然后把已匹配的從字符串中刪除,一直 while 循環(huán)匹配。
解析開始標(biāo)簽函數(shù)代碼:
function parseStartTag () {
// 標(biāo)簽的開始 如<div
const start = html.match(startTagOpen)
if (start) {
const match = {
tagName: start[1], // 標(biāo)簽名稱
attrs: [], // 標(biāo)簽屬性
start: index // 開始位置
}
// 減去已匹配的長(zhǎng)度
advance(start[0].length)
let end, attr
while (!(end = html.match(startTagClose)) && (attr = html.match(dynamicArgAttribute) || html.match(attribute))) {
attr.start = index
v
advance(attr[0].length)
attr.end = index
match.attrs.push(attr) // 把匹配到的屬性添加到attrs數(shù)組
}
if (end) { // 標(biāo)簽的結(jié)束符 ">"
match.unarySlash = end[1]
advance(end[0].length) // 減去已匹配的長(zhǎng)度
match.end = index // 結(jié)束位置
return match
}
}
}
處理過后結(jié)構(gòu)如下:
接下來就是處理組合屬性,調(diào)用 “handleStartTag” 函數(shù)
function handleStartTag (match) {
const tagName = match.tagName // 標(biāo)簽名稱
const unarySlash = match.unarySlash // 一元標(biāo)簽
if (expectHTML) {
if (lastTag === 'p' && isNonPhrasingTag(tagName)) {
// 解析標(biāo)簽結(jié)束
parseEndTag(lastTag)
}
if (canBeLeftOpenTag(tagName) && lastTag === tagName) {
parseEndTag(tagName)
}
}
// 是否為一元標(biāo)簽
const unary = isUnaryTag(tagName) || !!unarySlash
const l = match.attrs.length
// 標(biāo)簽屬性集合
const attrs = new Array(l)
for (let i = 0; i < l; i++) {
const args = match.attrs[i]
const value = args[3] || args[4] || args[5] || ''
const shouldDecodeNewlines = tagName === 'a' && args[1] === 'href' ? options.shouldDecodeNewlinesForHref : options.shouldDecodeNewlines
attrs[i] = {
name: args[1], // 屬性名稱
value: decodeAttr(value, shouldDecodeNewlines) // 屬性值
}
if (process.env.NODE_ENV !== 'production' && options.outputSourceRange) {
// 開始位置
attrs[i].start = args.start + args[0].match(/^\s*/).length
// 結(jié)束位置
attrs[i].end = args.end
}
}
if (!unary) {
stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs, start: match.start, end: match.end })
lastTag = tagName
}
// 調(diào)用start函數(shù)
if (options.start) {
options.start(tagName, attrs, unary, match.start, match.end)
}
}
我們簡(jiǎn)單說一下最后調(diào)用的start函數(shù)的作用:
1、判斷是否為svg標(biāo)簽,并處理svg在ie下的兼容性問題
2、遍歷標(biāo)簽屬性,驗(yàn)證其名稱是否有效
3、標(biāo)簽名是否為 style 或者 script ,如果在服務(wù)端會(huì)提示warn警告
4、檢查屬性是否存在 v-for、v-if、v-once指令
5、如果是更元素就驗(yàn)證其合法性,不能是 slot 和 template 標(biāo)簽,不能存在 v-for指令
以上就是界面html模板的開始標(biāo)簽的分析,接下來我們來分析如何匹配結(jié)束標(biāo)簽。
請(qǐng)看:Vue源碼全面解析三十 parseHTML函數(shù)(解析html(二)結(jié)束標(biāo)簽)
如有錯(cuò)誤,歡迎指正,謝謝。
家好,我是Echa 哥,祝大家開工大吉!萬事如意!
vue作為前端主流的3大框架之一,目前在國(guó)內(nèi)有著非常廣泛的應(yīng)用,由于其輕量和自底向上的漸進(jìn)式設(shè)計(jì)思想,使其不僅僅被應(yīng)用于PC系統(tǒng),對(duì)于移動(dòng)端,桌面軟件(electronjs)等也有廣泛的應(yīng)用,與此誕生的優(yōu)秀的開源框架比如elementUI,iView, ant-design-vue等也極大的降低了開發(fā)者的開發(fā)成本,并極大的提高了開發(fā)效率。筆者最初接觸vue時(shí)也是使用的iview框架,親自體會(huì)之后確實(shí)非常易用且強(qiáng)大。
筆者曾經(jīng)有兩年的vue項(xiàng)目經(jīng)驗(yàn),基于vue做過移動(dòng)端項(xiàng)目和PC端的ERP系統(tǒng),雖然平時(shí)工作中采用的是react技術(shù)棧,但平時(shí)還是會(huì)積累很多vue相關(guān)的最佳實(shí)踐和做一些基于vue的開源項(xiàng)目,所以說總結(jié)vue的項(xiàng)目經(jīng)驗(yàn)我覺得是最好的成長(zhǎng),也希望給今年想接觸vue框架或者想從事vue工作的朋友帶來一些經(jīng)驗(yàn)和思考。
你將收獲
本文不僅僅是總結(jié)一些vue使用踩過的一些坑和項(xiàng)目經(jīng)驗(yàn),更多的是使用框架(vue/react)過程中的方法論和組件的設(shè)計(jì)思路,最后還會(huì)有一些個(gè)人對(duì)工程化的一些總結(jié),希望有更多經(jīng)驗(yàn)的朋友們可以一起交流,探索vue的奧妙。
在開始文章之前,筆者建議大家對(duì)javascript, css, html基礎(chǔ)有一定的了解,因?yàn)闀?huì)用框架不一定能很好的實(shí)現(xiàn)業(yè)務(wù)需求和功能,要想實(shí)現(xiàn)不同場(chǎng)景下不同復(fù)雜度的需求,一定要對(duì)web基礎(chǔ)有充足的了解,所以希望大家熟悉如下基礎(chǔ)知識(shí),如果不太熟悉可以花時(shí)間研究了解一下。
javascript:
css:
html:
所以希望大家掌握好以上基礎(chǔ)知識(shí),也是前端開發(fā)的基礎(chǔ),接下來我們直接進(jìn)入正文。
?
vue學(xué)習(xí)最快的方式就是實(shí)踐,根據(jù)官網(wǎng)多寫幾個(gè)例子是掌握vue最快的方式。 接下來筆者就來總結(jié)一下在開發(fā)vue項(xiàng)目中的一些實(shí)踐經(jīng)驗(yàn)。
?
以上是vue官網(wǎng)上的生命周期的方法,大致劃分一下分為創(chuàng)建前/后,掛載前/后,更新前/后,銷毀前/后這四個(gè)階段。各個(gè)階段的狀態(tài)總結(jié)如下:
根據(jù)以上介紹,頁(yè)面第一次加載時(shí)會(huì)執(zhí)行 beforeCreate, created, beforeMount, mounted這四個(gè)生命周期,所以我們一般在created階段處理http請(qǐng)求獲取數(shù)據(jù)或者對(duì)data做一定的處理, 我們會(huì)在mounted階段操作dom,比如使用jquery,或者其他第三方dom庫(kù)。其次,根據(jù)以上不同周期下數(shù)據(jù)和頁(yè)面狀態(tài)的不同,我們還可以做其他更多操作,所以說每個(gè)生命周期的發(fā)展?fàn)顟B(tài)非常重要,一定要理解,這樣才能對(duì)vue有更多的控制權(quán)。
指令 (Directives) 是帶有 v- 前綴的特殊屬性,vue常用的指令有:
以上是比較常用的指令,具體用法就不一一舉例了,其中v-cloak主要是用來避免頁(yè)面加載時(shí)出現(xiàn)閃爍的問題,可以結(jié)合css的[v-cloak] { display: none }方式解決這一問題。關(guān)于指令的動(dòng)態(tài)參數(shù),使用也很簡(jiǎn)單,雖然是2.6.0 新增的,但是方法很靈活,具體使用如下:
<a v-on:[eventName]="doSomething"> ... </a>
復(fù)制代碼
我們可以根據(jù)具體情況動(dòng)態(tài)切換事件名,從而綁定同一個(gè)函數(shù)。
<Tag @click.native="handleClick">ok</Tag>
復(fù)制代碼
用法如下:
<input type="text" v-model.trim="value">
復(fù)制代碼
還有很多修飾符比如鍵盤,鼠標(biāo)等修飾符,感興趣的大家可以自行學(xué)習(xí)研究。
組件之間的通信方案:
父子組件:
組件的按需加載是項(xiàng)目性能優(yōu)化的一個(gè)環(huán)節(jié),也可以降低首屏渲染時(shí)間,筆者在項(xiàng)目中用到的組件按需加載的方式如下:
<template>
<div>
<ComponentA />
<ComponentB />
</div>
</template>
<script>
const ComponentA = () => import('./ComponentA')
const ComponentB = () => import('./ComponentB')
export default {
// ...
components: {
ComponentA,
ComponentB
},
// ...
}
</script>
復(fù)制代碼
<template>
<div>
<ComponentA />
</div>
</template>
<script>
const ComponentA = resolve => require(['./ComponentA'], resolve)
export default {
// ...
components: {
ComponentA
},
// ...
}
</script>
復(fù)制代碼
?
Vuex 是一個(gè)專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式。它采用集中式存儲(chǔ)管理應(yīng)用的所有組件的狀態(tài),并以相應(yīng)的規(guī)則保證狀態(tài)以一種可預(yù)測(cè)的方式發(fā)生變化。
?
vuex的基本工作模式如下圖所示:
state的改變完全由mutations控制, 我們也沒必要任何項(xiàng)目都使用vuex,對(duì)于中大型復(fù)雜項(xiàng)目而言,需要共享的狀態(tài)很多時(shí),使用vuex才是最佳的選擇。接下來我將詳細(xì)介紹各api的概念和作用。
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}
})
// 訪問getters里的屬性
this.$store.getters.doneTodos
復(fù)制代碼
const store = new Vuex.Store({
state: {
num: 1
},
mutations: {
add (state) {
// 變更狀態(tài)
state.num++
}
}
})
// 在項(xiàng)目中使用mutation
store.commit('add')
// 添加額外參數(shù)
store.commit('add', 10)
復(fù)制代碼
const store = new Vuex.Store({
state: {
num: 0
},
mutations: {
add (state) {
state.num++
}
},
actions: {
add (context) {
context.commit('add')
},
asyncAdd ({ commit }) {
setTimeout(() => {
commit('add')
}
}
})
// 分發(fā)action
store.dispatch('add')
// 異步action
store.dispatch('asyncAdd')
// 異步傳參
store.dispatch('asyncAdd', { num: 10 })
筆者更具實(shí)際經(jīng)驗(yàn)總結(jié)了一套標(biāo)準(zhǔn)使用模式,就拿筆者之前的開源XPXMS舉例,如下:
store目錄是用來組織vuex代碼用的,我將action,mutation,state分文件管理,這樣項(xiàng)目大了之后也很容易管理和查詢。接下來看看是如何組織的:
// type.ts
// 用來定義state等的類型文件
export interface State {
name: string;
isLogin: boolean;
config: Config;
[propName: string]: any; // 用來定義可選的額外屬性
}
export interface Config {
header: HeaderType,
banner: Banner,
bannerSider: BannerSider,
supportPay: SupportPay
}
export interface Response {
[propName: string]: any;
}
// state.ts
// 定義全局狀態(tài)
import { State } from './type'
export const state: State = {
name: '',
isLogin: false,
curScreen: '0', // 0為pc, 1為移動(dòng)
config: {
header: {
columns: ['首頁(yè)', '產(chǎn)品', '技術(shù)', '運(yùn)營(yíng)', '商業(yè)'],
height: '50',
backgroundColor: '#000000',
logo: ''
}
},
// ...
articleDetail: null
};
// mutation.ts
import {
State,
Config,
HeaderType,
Banner,
BannerSider,
SupportPay
} from './type'
export default {
// 預(yù)覽模式
setScreen(state: State, payload: string) {
state.curScreen = payload;
},
// 刪除banner圖
delBanner(state: State, payload: number) {
state.config.banner.bannerList.splice(payload, 1);
},
// 添加banner圖
addBanner(state: State, payload: object) {
state.config.banner.bannerList.push(payload);
},
// ...
};
// action.ts
import {
HeaderType,
Response
} from './type'
import http from '../utils/http'
import { uuid, formatTime } from '../utils/common'
import { message } from 'ant-design-vue'
export default {
/**配置 */
setConfig(context: any, paylod: HeaderType) {
http.get('/config/all').then((res:Response) => {
context.commit('setConfig', res.data)
}).catch((err:any) => {
message.error(err.data)
})
},
/**header */
saveHeader(context: any, paylod: HeaderType) {
http.post('/config/setHeader', paylod).then((res:Response) => {
message.success(res.data)
context.commit('saveHeader', paylod)
}).catch((err:any) => {
message.error(err.data)
})
},
// ...
};
// index.ts
import Vue from 'vue';
import Vuex from 'vuex';
import { state } from './state';
import mutations from './mutation';
import actions from './action';
Vue.use(Vuex);
export default new Vuex.Store({
state,
mutations,
actions
});
// main.ts
// 最后掛載到入口文件的vue實(shí)例上
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store/';
import './component-class-hooks';
import './registerServiceWorker';
Vue.config.productionTip = false;
new Vue({
router,
store,
render: (h) => h(App),
}).$mount('#app');
我們?cè)趯?shí)際項(xiàng)目中都可以使用這種方式組織管理vuex相關(guān)的代碼。
vue-router使用大家想必不是很陌生,這里直接寫一個(gè)案例:
// router.ts
import Vue from 'vue';
import Router from 'vue-router';
import Home from './views/admin/Home.vue';
Vue.use(Router);
const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
component: Home,
beforeEnter: (to, from, next) => {
next();
},
children: [
{
// 當(dāng) /user/:id/profile 匹配成功,
// UserProfile 會(huì)被渲染在 User 的 <router-view> 中
path: '',
name: 'header',
component: () => import(/* webpackChunkName: "header" */ './views/admin/subpage/Header.vue'),
},
{
path: '/banner',
name: 'banner',
component: () => import(/* webpackChunkName: "banner" */ './views/admin/subpage/Banner.vue'),
},
{
path: '/admin',
name: 'admin',
component: () => import(/* webpackChunkName: "admin" */ './views/admin/Admin.vue'),
},
],
},
{
path: '/login',
name: 'login',
component: () => import(/* webpackChunkName: "login" */ './views/Login.vue'),
meta:{
keepAlive:false //不需要被緩存的組件
}
},
{
path: '*',
name: '404',
component: () => import(/* webpackChunkName: "404" */ './views/404.vue'),
},
],
});
// 路由導(dǎo)航鉤子的用法
router.beforeEach((to, from, next) => {
if(from.path.indexOf('/preview') < 0) {
sessionStorage.setItem('prevToPreviewPath', from.path);
}
next();
})
export default router
以上案例是很典型的靜態(tài)路由配置和導(dǎo)航鉤子的用法(如何加載路由組件,動(dòng)態(tài)加載路由組件,404頁(yè)面路由配置,路由導(dǎo)航鉤子使用)。如果在做后臺(tái)系統(tǒng),往往會(huì)涉及到權(quán)限系統(tǒng),所以一般會(huì)采用動(dòng)態(tài)配置路由,通過前后端約定的路由方式,路由配置文件更具不同用戶的權(quán)限由后端處理后返。由于設(shè)計(jì)細(xì)節(jié)比較繁瑣,涉及到前后端協(xié)定,所以這里只講思路就好了。
受現(xiàn)代 JavaScript 的限制,Vue 無法檢測(cè)到對(duì)象屬性的添加或刪除。由于 Vue 會(huì)在初始化實(shí)例時(shí)對(duì)屬性執(zhí)行 getter/setter 轉(zhuǎn)化,所以屬性必須在 data 對(duì)象上存在才能讓 Vue 將它轉(zhuǎn)換為響應(yīng)式的。還有一種情況是,vue無法檢測(cè)到data屬性值為數(shù)組或?qū)ο蟮男薷模晕覀冃枰迷瓕?duì)象與要混合進(jìn)去的對(duì)象的屬性一起創(chuàng)建一個(gè)新的對(duì)象。可以使用this.$set或者對(duì)象的深拷貝,如果是數(shù)組則可以使用splice,擴(kuò)展運(yùn)算符等方法來更新。
keep-alive是Vue的內(nèi)置組件,能在組件切換過程中將狀態(tài)保留在內(nèi)存中,防止重復(fù)渲染DOM。我們可以使用以下方式設(shè)置某些頁(yè)面是否被緩存:
// routes 配置
export default [
{
path: '/A',
name: 'A',
component: A,
meta: {
keepAlive: true // 需要被緩存
}
}, {
path: '/B',
name: 'B',
component: B,
meta: {
keepAlive: false // 不需要被緩存
}
}
]
路由視圖配置:
// 路由設(shè)置
<keep-alive>
<router-view v-if="$route.meta.keepAlive">
<!-- 會(huì)被緩存的視圖組件-->
</router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive">
<!-- 不需要緩存的視圖組件-->
</router-view>
<template>
<div id="app">
<keep-alive>
<router-view :key="key" />
</keep-alive>
</div>
</template>
<script lang="ts">
import { Vue } from 'vue-property-decorator';
import Component from 'vue-class-component';
@Component
export default class App extends Vue {
get key() {
// 緩存除預(yù)覽和登陸頁(yè)面之外的其他頁(yè)面
console.log(this.$route.path)
if(this.$route.path.indexOf('/preview') > -1) {
return '0'
}else if(this.$route.path === '/login') {
return '1'
}else {
return '2'
}
}
}
</script>
總結(jié)一下筆者在vue項(xiàng)目中的常用的工具函數(shù)。
/**
* 識(shí)別ie--淺識(shí)別
*/
export const isIe = () => {
let explorer = window.navigator.userAgent;
//判斷是否為IE瀏覽器
if (explorer.indexOf("MSIE") >= 0) {
return true;
}else {
return false
}
}
/**
* 顏色轉(zhuǎn)換16進(jìn)制轉(zhuǎn)rgba
* @param {String} hex
* @param {Number} opacity
*/
export function hex2Rgba(hex, opacity) {
if(!hex) hex = "#2c4dae";
return "rgba(" + parseInt("0x" + hex.slice(1, 3)) + "," + parseInt("0x" + hex.slice(3, 5)) + "," + parseInt("0x" + hex.slice(5, 7)) + "," + (opacity || "1") + ")";
}
// 去除html標(biāo)簽
export const htmlSafeStr = (str) => {
return str.replace(/<[^>]+>/g, "")
}
/* 獲取url參數(shù) */
export const getQueryString = () => {
let qs = location.href.split('?')[1] || '',
args = {},
items = qs.length ? qs.split("&") : [];
items.forEach((item,i) => {
let arr = item.split('='),
name = decodeURIComponent(arr[0]),
value = decodeURIComponent(arr[1]);
name.length && (args[name] = value)
})
return args;
}
/* 解析url參數(shù) */
export const paramsToStringify = (params) => {
if(params){
let query = [];
for(let key in params){
query.push(`${key}=${params[key]}`)
}
return `${query.join('&')}`
}else{
return ''
}
}
export const toArray = (data) => {
return Array.isArray(data) ? data : [data]
}
/**
* 帶參數(shù)跳轉(zhuǎn)url(hash模式)
* @param {String} url
* @param {Object} params
*/
export const toPage = (url, params) => {
if(params){
let query = [];
for(let key in params){
query.push(`${key}=${params[key]}`)
}
window.location.href = `./index.html#/${url}?${query.join('&')}`;
}else{
window.location.href = `./index.html#/${url}`;
}
}
/**
* 指定字符串 溢出顯示省略號(hào)
* @param {String} str
* @param {Number} num
*/
export const getSubStringSum = (str = "", num = 1) => {
let newStr;
if(str){
str = str + '';
if (str.trim().length > num ) {
newStr = str.trim().substring(0, num) + "...";
} else {
newStr = str.trim();
}
}else{
newStr = ''
}
return newStr;
}
/**
* 生成uuid
* @param {number} len 生成指定長(zhǎng)度的uuid
* @param {number} radix uuid進(jìn)制數(shù)
*/
export function uuid(len, radix) {
let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
let uuid = [], i;
radix = radix || chars.length;
if (len) {
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
} else {
let r;
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random()*16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
}
/**
* 生成指定格式的時(shí)間
* @param {*} timeStemp 時(shí)間戳
* @param {*} flag 格式符號(hào)
*/
export function formatTime(timeStemp, flag) {
let time = new Date(timeStemp);
let timeArr = [time.getFullYear(), time.getMonth() + 1, time.getDate()];
return timeArr.join(flag || '/')
}
這個(gè)主要是對(duì)axios的理解,大家可以學(xué)習(xí)axios官方文檔,這里給出一個(gè)二次封裝的模版:
import axios from 'axios'
import qs from 'qs'
// 請(qǐng)求攔截
axios.interceptors.request.use(config => {
// 此處可以封裝一些加載狀態(tài)
return config
}, error => {
return Promise.reject(error)
})
// 響應(yīng)攔截
axios.interceptors.response.use(response => {
return response
}, error => {
return Promise.resolve(error.response)
})
function checkStatus (response) {
// 此處可以封裝一些加載狀態(tài)
// 如果http狀態(tài)碼正常,則直接返回?cái)?shù)據(jù)
if(response) {
if (response.status === 200 || response.status === 304) {
return response.data
// 如果不需要除了data之外的數(shù)據(jù),可以直接 return response.data
} else if (response.status === 401) {
location.href = '/login';
} else {
throw response.data
}
} else {
throw {data:'網(wǎng)絡(luò)錯(cuò)誤'}
}
}
// axios默認(rèn)參數(shù)配置
axios.defaults.baseURL = '/api/v0';
axios.defaults.timeout = 10000;
// restful API封裝
export default {
post (url, data) {
return axios({
method: 'post',
url,
data: qs.stringify(data),
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).then(
(res) => {
return checkStatus(res)
}
)
},
get (url, params) {
return axios({
method: 'get',
url,
params, // get 請(qǐng)求時(shí)帶的參數(shù)
headers: {
'X-Requested-With': 'XMLHttpRequest'
}
}).then(
(res) => {
return checkStatus(res)
}
)
},
del (url, params) {
return axios({
method: 'delete',
url,
params, // get 請(qǐng)求時(shí)帶的參數(shù)
headers: {
'X-Requested-With': 'XMLHttpRequest'
}
}).then(
(res) => {
return checkStatus(res)
}
)
}
}
該模版只是一個(gè)大致框架,大家可以細(xì)化成業(yè)務(wù)需求的樣子,該案例提供了restful接口方法,比如get/post/delete/put等。
筆者在做vue項(xiàng)目時(shí)為了提高開發(fā)效率也會(huì)直接用第三方插件,下面整理一下常用的vue社區(qū)組件和庫(kù)。
更多組件可以在vue插件社區(qū)查看。
在講完vue項(xiàng)目經(jīng)驗(yàn)之后,為了讓大家能獨(dú)立負(fù)責(zé)一個(gè)項(xiàng)目,我們還需要知道從0開始搭建項(xiàng)目的步驟,以及通過項(xiàng)目實(shí)際情況,自己配置一個(gè)符合的項(xiàng)目框架,比如有些公司會(huì)采用vue+element+vue+less搭建,有些公司采用vue+iview+vue+sass,或者其他更多的技術(shù)棧,所以我們要有把控能力,我們需要熟悉webpack或者vue-cli3腳手架的配置,筆者之前有些過詳細(xì)的webpack和vue-cli3搭建自定義項(xiàng)目的文章,這里由于篇幅有限就不一一舉例了。感興趣的朋友可以參考以下兩篇文章:
?
組件系統(tǒng)是 Vue 的另一個(gè)重要概念,因?yàn)樗且环N抽象,允許我們使用小型、獨(dú)立和通常可復(fù)用的組件構(gòu)建大型應(yīng)用。幾乎任意類型的應(yīng)用界面都可以抽象為一個(gè)組件樹。在一個(gè)大型應(yīng)用中,有必要將整個(gè)應(yīng)用程序劃分為組件,以使開發(fā)更易管理。
?
對(duì)于一個(gè)基礎(chǔ)組件來說,我們?cè)撊绾蜗率秩ピO(shè)計(jì)呢?首先筆者覺得應(yīng)該先從需求和功能入手,先劃分好組件的功能邊界,組件能做什么,理清這些之后再開始寫組件。
如上圖組件的一個(gè)抽象,我們無論如何記住的第一步就是先理清需求在去著手開發(fā),這樣可以避免大量效率的丟失。在上圖中我們要注意組件的解耦合,每個(gè)組件都負(fù)責(zé)特定的功能或者展現(xiàn),這樣對(duì)組件后期維護(hù)性和擴(kuò)展性有非常大的幫助。筆者總結(jié)了一下組件設(shè)計(jì)的注意事項(xiàng):
筆者拿之前在開源社區(qū)發(fā)布的一個(gè)文件上傳組件為例子來說明舉例,代碼如下:
<template>
<div>
<a-upload
:action="action"
listType="picture-card"
:fileList="fileList"
@preview="handlePreview"
@change="handleChange"
:remove="delFile"
:data="data"
>
<template v-if="!fileList.length && defaultValue">
<img :src="defaultValue" alt="" style="width: 100%">
</template>
<template v-else>
<div v-if="fileList.length < 2">
<a-icon type="plus" />
<div class="ant-upload-text">上傳</div>
</div>
</template>
</a-upload>
<a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
<img alt="example" style="width: 100%" :src="previewImage" />
</a-modal>
</div>
</template>
<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';
@Component
export default class Upload extends Vue {
@Prop({ default: 'https://www.mocky.io/v2/5cc8019d300000980a055e76' })
action!: string;
@Prop()
defaultValue: string;
@Prop()
data: object;
@Prop({ default: function() {} })
onFileDel: any;
@Prop({ default: function() {} })
onFileChange: any;
public previewVisible: boolean = false;
public previewImage: string = '';
public fileList: object[] = [];
// 預(yù)覽圖片
public handlePreview(file: any) {
this.previewImage = file.url || file.thumbUrl;
this.previewVisible = true;
}
// 刪除文件和回調(diào)
public delFile(file: any) {
this.fileList = [];
this.onFileDel();
}
// 文件上傳變化的處理函數(shù)
public handleChange({ file }: any) {
this.fileList = [file];
if(file.status === 'done') {
this.onFileChange(file.response.url);
} else if(file.status === 'error') {
this.$message.error(file.response.msg)
}
}
// 取消預(yù)覽
public handleCancel() {
this.previewVisible = false;
}
}
</script>
以上文件上傳預(yù)覽采用的是ts來實(shí)現(xiàn),但設(shè)計(jì)思路都是一致的,大家可以參考交流一下。 關(guān)于如何設(shè)計(jì)一個(gè)健壯的組件,筆者也寫過相關(guān)文章,大致思想都好似一樣的,可以參考一下:
組件的設(shè)計(jì)思想和方法與具體框架無關(guān),所以組件設(shè)計(jì)的核心是方法論,我們只有在項(xiàng)目中不斷總結(jié)和抽象,才能對(duì)組件設(shè)計(jì)有更深刻的理解。
這里是筆者總結(jié)的一套思維導(dǎo)圖:
有點(diǎn)微前端架構(gòu)的感覺,但是還有很多細(xì)節(jié)需要考慮。此架構(gòu)適用于不同子系統(tǒng)獨(dú)立部署和開發(fā)的環(huán)境, 也不需要考慮具體的技術(shù)棧選擇,相同的框架采用同一套自建組件庫(kù)來達(dá)到組件的復(fù)用,這里提倡項(xiàng)目開始設(shè)計(jì)時(shí)就考慮組件化和模塊化,做出功能的最大的拆分和去耦合。筆者后面會(huì)單獨(dú)花時(shí)間總結(jié)微前端架構(gòu)具體的一些設(shè)計(jì)思路和落地方案,感興趣的可以一起探討交流。
*請(qǐng)認(rèn)真填寫需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。