本文介绍了 mpvue+vuex 搭建小程序详细教程 (完整步骤), 分享给大家, 具体如下:
源码
https://GitHub.com/davidlin88/mpvue-vuex-demo
构成
1, 采用 mpvue 官方脚手架搭建项目底层结构
2, 采用 Fly.JS 作为 http 请求库
3, 引入 mpvue-router-patach, 以便在 mpvue 小程序中能使用 vue-router 的写法
目录结构
├── src // 我们的项目的源码编写文件
│ ├── components // 组件目录
│ ├── common // 静态资源
│ │ └── font // iconfont 图标
│ │ └── img // 图片
│ │ └── JS // JS
│ │ │└── mixins.JS // JS
│ │ │└── tips.JS // JS
│ │ │└── utils.JS // JS
│ │ └── SCSS // SCSS 样式
│ │ │└── base.SCSS // 自定义样式
│ │ │└── icon.SCSS // iconfont 图标
│ │ │└── index.SCSS // 基础汇总
│ │ │└── mixin.SCSS // 混合等工具样式
│ │ │└── reset.SCSS // 初始化样式
│ │ │└── variable.SCSS // 全局主题色样式
│ ├── http //http 请求配置文件
│ │ └── API // 接口调用文件
│ │ └── config //fly 配置文件
│ ├── pages // 项目页面目录
│ ├── components // 项目复用组件目录
│ ├── store // 状态管理 vuex 配置目录
│ │ └── actions.JS //actions 异步修改状态
│ │ └── getters.JS //getters 计算过滤操作
│ │ └── mutation-types.JS //mutations 类型
│ │ └── mutations.JS // 修改状态
│ │ └── index.JS // 我们组装模块并导出 store 的地方
│ │ └── state.JS // 数据源定义
│ ├── untils // 工具函数目录
│ │ └── index.JS
│ ├── App.vue // App 入口文件
│ ├── main.JS // 主配置文件
│ ├── config.JS // host 等配置
快速创建一个 mpvue 项目
- # 全局安装 vue-cli
- $ NPM install -g vue-cli
- # 创建一个基于 mpvue-quickstart 模板的新项目, 记得选择安装 vuex
- $ vue init mpvue/mpvue-quickstart mpvue-demo
- # 安装 fly
- $ NPM i flyio --save
- # 安装依赖
- $ cd mpvue-demo
- $ NPM i
- # 启动构建
- $ NPM run dev
配置 fly
1, 配置公共设置
- 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'
- // 配置请求基地址
- // // 定义公共 headers
- // fly.config.headers={xx:5,bb:6,dd:7}
- // // 设置超时
- fly.config.timeout = 20000;
- // // 设置请求基地址
- fly.config.baseURL = config.host
- // 添加请求拦截器
- fly.interceptors.request.use((request) => {
- // 给所有请求添加自定义 header
- request.headers["X-Tag"] = "flyio";
- // 打印出请求体
- // console.log(request.body)
- // 终止请求
- //var err=new Error("xxx")
- //err.request=request
- //return Promise.reject(new Error(""))
- // 可以显式返回 request, 也可以不返回, 没有返回值时拦截器中默认返回 request
- return request;
- })
- // 添加响应拦截器, 响应拦截器会在 then/catch 处理之前执行
- fly.interceptors.response.use(
- (response) => {
- // 只将请求结果的 data 字段返回
- return response.data
- },
- (err) => {
- // 发生网络错误后会走到这里
- //return Promise.resolve("ssss")
- }
- )
- // Vue.prototype.$http=fly // 将 fly 实例挂在 vue 原型上
- export default fly
2, 配置个性设置
- 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 请求
- export const get = (params) => {
- return fly.get(`${host}${params.url}`, qs.stringify(params.data))
- };
- // 通用的 post 请求
- export const post = (params) => {
- return fly.post(`${host}${params.url}`, qs.stringify(params.data))
- };
- // 封装的登录请求, 根据后台接收方式选择是否加 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, 目录结构
│ ├── store // 状态管理 vuex 配置目录
│ │ └── actions.JS //actions 异步修改状态
│ │ └── getters.JS //getters 计算过滤操作
│ │ └── mutation-types.JS //mutations 类型
│ │ └── mutations.JS // 修改状态
│ │ └── index.JS // 我们组装模块并导出 store 的地方
│ │ └── state.JS // 数据源定义
2,main.JS 中引入 store, 并绑定到 Vue 构造函数的原型上, 这样在每个 vue 的组件都可以通过 this.$store 访问 store 对象.
- import store from './store/index'
- Vue.prototype.$store=store;
3, 定义初始变量 store/state.JS
- const state={
- openId: '',
- }
- export default state
4,mutation 类型
方便检测错误和书写, 一般写方法
- export const SET_OPEN_ID = 'SET_OPEN_ID'
- 5,store/mutations.JS
写处理方法
- import * as types from './mutation-types'
- const matations={
- /**
- * state: 当前状态树
- * v: 提交 matations 时传的参数
- */
- [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: 没有用到复杂计算, 因此没有引入 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, 结构更清晰
- _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 状态持久化 (缓存到本地)
store/index.hs 的 export default 中添加配置:
- // 引入 vuex-persistedstate, 将 vuex 的数据持久化到本地
- 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
遇到安装依赖后, 运行项目, 但 dist 下没有 App.JS 等入口文件的, 将 package.JSON 里的 mpvue-loader 的版本前的 ^ 去掉, 删除依赖, 重新安装即可
在 onLoad 周期内执行获取数据等初始化操作, 因为 mpvue 的 created 钩子执行要早得多 (小程序运行时)
来源: http://www.jb51.net/article/148306.htm