mpvue+vuex搭建小程序詳細(xì)教程(完整步驟)
本文介紹了mpvue+vuex搭建小程序詳細(xì)教程(完整步驟),分享給大家,具體如下:
源碼
構(gòu)成
1、采用mpvue 官方腳手架搭建項(xiàng)目底層結(jié)構(gòu)
2、采用Fly.js 作為http請(qǐng)求庫
3、引入mpvue-router-patach,以便在mpvue小程序中能使用vue-router的寫法
目錄結(jié)構(gòu)
├── src // 我們的項(xiàng)目的源碼編寫文件 │ ├── components // 組件目錄 │ ├── common //靜態(tài)資源 │ │ └── font // iconfont圖標(biāo) │ │ └── img // 圖片 │ │ └── js // js │ │ │└── mixins.js // js │ │ │└── tips.js // js │ │ │└── utils.js // js │ │ └── scss // scss樣式 │ │ │└── base.scss // 自定義樣式 │ │ │└── icon.scss // iconfont圖標(biāo) │ │ │└── index.scss // 基礎(chǔ)匯總 │ │ │└── mixin.scss // 混合等工具樣式 │ │ │└── reset.scss // 初始化樣式 │ │ │└── variable.scss // 全局主題色樣式 │ ├── http //http請(qǐng)求配置文件 │ │ └── api // 接口調(diào)用文件 │ │ └── config //fly 配置文件 │ ├── pages //項(xiàng)目頁面目錄 │ ├── components //項(xiàng)目復(fù)用組件目錄 │ ├── store //狀態(tài)管理 vuex配置目錄 │ │ └── actions.js //actions異步修改狀態(tài) │ │ └── getters.js //getters計(jì)算過濾操作 │ │ └── mutation-types.js //mutations 類型 │ │ └── mutations.js //修改狀態(tài) │ │ └── index.js //我們組裝模塊并導(dǎo)出 store 的地方 │ │ └── state.js //數(shù)據(jù)源定義 │ ├── untils //工具函數(shù)目錄 │ │ └── index.js │ ├── App.vue // APP入口文件 │ ├── main.js // 主配置文件 │ ├── config.js // host等配置
快速創(chuàng)建一個(gè)mpvue項(xiàng)目
# 全局安裝 vue-cli $ npm install -g vue-cli # 創(chuàng)建一個(gè)基于 mpvue-quickstart 模板的新項(xiàng)目,記得選擇安裝vuex $ vue init mpvue/mpvue-quickstart mpvue-demo # 安裝fly $ npm i flyio --save # 安裝依賴 $ cd mpvue-demo $ npm i # 啟動(dòng)構(gòu)建 $ npm run dev
配置fly
1、配置公共設(shè)置
src/http/config.js
/*
fly配置文件
by:David 2018.6.14
*/
//引入 fly
var Fly = require("flyio/dist/npm/wx")
var fly = new Fly;
import config from '@/config'
//配置請(qǐng)求基地址
// //定義公共headers
// fly.config.headers={xx:5,bb:6,dd:7}
// //設(shè)置超時(shí)
fly.config.timeout = 20000;
// //設(shè)置請(qǐng)求基地址
fly.config.baseURL = config.host
//添加請(qǐng)求攔截器
fly.interceptors.request.use((request) => {
//給所有請(qǐng)求添加自定義header
request.headers["X-Tag"] = "flyio";
//打印出請(qǐng)求體
// console.log(request.body)
//終止請(qǐng)求
//var err=new Error("xxx")
//err.request=request
//return Promise.reject(new Error(""))
//可以顯式返回request, 也可以不返回,沒有返回值時(shí)攔截器中默認(rèn)返回request
return request;
})
//添加響應(yīng)攔截器,響應(yīng)攔截器會(huì)在then/catch處理之前執(zhí)行
fly.interceptors.response.use(
(response) => {
//只將請(qǐng)求結(jié)果的data字段返回
return response.data
},
(err) => {
//發(fā)生網(wǎng)絡(luò)錯(cuò)誤后會(huì)走到這里
//return Promise.resolve("ssss")
}
)
// Vue.prototype.$http=fly //將fly實(shí)例掛在vue原型上
export default fly
2、配置個(gè)性設(shè)置
src/http/api.js
import fly from './config'
import qs from 'qs'
import config from '../config'
const host = config.host;
const appKey = config.appKey;
const appid = config.appid;
/**
* 接口模版====post
*
* export const test = params => {return fly.post(`${root}/xx/xx`, qs.stringify(params))};
*
* 接口模版====get
*
* export const test1 = function(){return fly.get(`${root}/api/getNewsList`)}
*
*
* 用法:
* 在 頁面用引入 test
* import {test} from '../../http/api.js'
*
* test(params).then(res=>{ console.log(res) })
*/
// 通用的get請(qǐng)求
export const get = (params) => {
return fly.get(`${host}${params.url}`, qs.stringify(params.data))
};
// 通用的post請(qǐng)求
export const post = (params) => {
return fly.post(`${host}${params.url}`, qs.stringify(params.data))
};
// 封裝的登錄請(qǐng)求,根據(jù)后臺(tái)接收方式選擇是否加qs.stringify
export const login = params => {
return fly.post('/login', params)
};
host配置
config.js
const host = 'http://xxx.xxx';
const appid = '';
const appKey = '';
const config = {
host,
appid,
appKey,
}
export default config
配置vuex
1、目錄結(jié)構(gòu)
│ ├── store //狀態(tài)管理 vuex配置目錄 │ │ └── actions.js //actions異步修改狀態(tài) │ │ └── getters.js //getters計(jì)算過濾操作 │ │ └── mutation-types.js //mutations 類型 │ │ └── mutations.js //修改狀態(tài) │ │ └── index.js //我們組裝模塊并導(dǎo)出 store 的地方 │ │ └── state.js //數(shù)據(jù)源定義
2、main.js中引入store, 并綁定到Vue構(gòu)造函數(shù)的原型上,這樣在每個(gè)vue的組件都可以通過this.$store訪問store對(duì)象。
import store from './store/index' Vue.prototype.$store=store;
3、定義初始變量store/state.js
const state={
openId: '',
}
export default state
4、mutation類型
方便檢測(cè)錯(cuò)誤和書寫,一般寫方法
export const SET_OPEN_ID = 'SET_OPEN_ID'
5、store/mutations.js
寫處理方法
import * as types from './mutation-types'
const matations={
/**
* state:當(dāng)前狀態(tài)樹
* v: 提交matations時(shí)傳的參數(shù)
*/
[types.SET_OPEN_ID] (state, v) {
state.openId = v;
},
}
export default matations
6、store/index.js
匯總配置
import Vue from 'vue';
import Vuex from 'vuex';
import state from './state'
import mutations from './mutations'
Vue.use(Vuex);
export default new Vuex.Store({
state,
mutations,
})
使用vuex
ps:沒有用到復(fù)雜計(jì)算,因此沒有引入getters.js和actions.js
栗子:App.vue
<script>
import { login } from '@/http/api'
import { mapState, mapMutations } from 'vuex'
import { SET_OPEN_ID } from './store/mutation-types'
const App = getApp();
export default {
data: {
globalData: {}
},
computed: {
...mapState([
'openId'
])
},
methods: {
...mapMutations({
setOpenId: 'SET_OPEN_ID'
}),
// 使用了async+await的語法,用同步的方式寫異步腳本
async login(code) {
let _this = this;
try {
const resData = await login({ code: code });
if (resData.returnCode == 200) {
_this.setOpenId(resData.data.accountId)
}
} catch (err) {
console.error(err);
}
},
// 拆分wx.login,結(jié)構(gòu)更清晰
_login() {
let _this = this;
wx.login({
success(res) {
if (res.code) {
console.log('wx.login成功,code:', res.code);
let code = res.code;
_this.login(code)
} else {
_this.$tips.toast('微信登錄失敗')
}
}
});
}
},
onLaunch() {
this._login()
}
}
</script>
使用vuex-persistedstate,使vuex狀態(tài)持久化(緩存到本地)
store/index.hs的export default中添加配置:
// 引入vuex-persistedstate,將vuex的數(shù)據(jù)持久化到本地
export default new Vuex.Store({
state,
mutations,
getters,
actions,
plugins: [
createPersistedState({
storage: {
getItem: key => wx.getStorageSync(key),
setItem: (key, value) => wx.setStorageSync(key, value),
removeItem: key => {}
}
})
]
})
Tips
- 遇到安裝依賴后,運(yùn)行項(xiàng)目,但dist下沒有app.js等入口文件的,將package.json里的mpvue-loader的版本前的^去掉,刪除依賴,重新安裝即可
- 在onLoad周期內(nèi)執(zhí)行獲取數(shù)據(jù)等初始化操作,因?yàn)閙pvue的created鉤子執(zhí)行要早得多(小程序運(yùn)行時(shí))
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Vue.js 2.0窺探之Virtual DOM到底是什么?
大家可能聽說Vue.js 2.0已經(jīng)發(fā)布,并且在其中新添加如了一些新功能。其中一個(gè)功能就是“Virtual DOM”。那么下面這篇文章就來給大家詳細(xì)介紹Vue.js 2.0中的Virtual DOM到底是什么?需要的朋友可以參考借鑒,下面來一起看看吧。2017-02-02
Vue中調(diào)用組件使用kebab-case短橫線命名法和使用大駝峰的區(qū)別詳解
這篇文章主要介紹了Vue中調(diào)用組件使用kebab-case(短橫線)命名法和使用大駝峰的區(qū)別,通過實(shí)例可以看出如果是在html中使用組件,那么就不能用大駝峰式寫法,如果是在.vue?文件中就可以,需要的朋友可以參考下2023-10-10
詳解如何在Vue項(xiàng)目中導(dǎo)出Excel
這篇文章主要介紹了如何在Vue項(xiàng)目中導(dǎo)出Excel,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04
使用vue.js寫一個(gè)tab選項(xiàng)卡效果
Vue 實(shí)現(xiàn) Tab切換實(shí)現(xiàn)的場(chǎng)景很多,比如,利用vue-router、利用第三方插件、利用組件等等.本文使用組件來實(shí)踐tab選項(xiàng)卡2017-03-03

