笔者使用的是wepy,没有真正在实战项目中使用mpv,今天看了一下公司同事的项目mpv,感觉都差不多。
1、搭建
http://mpvue.com/mpvue/
2、安装完之后。
你会发现目录下多了个 disk 文件夹。
3、使用微信小程序工具打开 disk文件下面的文件就可以打开工程了。
出现这样的错误:
✘ http://eslint.org/docs/rules/indent Expected indentation of 6 spaces but found 8
src\pages\Main.vue:91:1
msg: 'Welcome to Your Vue.js App'
^
✘ http://eslint.org/docs/rules/indent Expected indentation of 4 spaces but found 6
src\pages\Main.vue:92:1
}
解决方法:
1、在创建工程的时候 Use ESLint tolint your code? 选择 n
2、选择Y,去到,工程设置里修改
在bulid/webpack.base.conf.js里面有配置如下:module: {rules: [...(config.dev.useEslint ? [createLintingRule()] : []),复制代码点进config.dev.useEslint,发现在config/index.js里配置useEslint: true, // 改为false即可。
router-patch 路由跳转:
小程序官网是:
wx.navigateTo:跳转到某个页面。会产生一个新的页面
wx.redirectTo:重定向到某个页面。替换掉当前页面
wx.switchTab:切换
tabwx.reLaunch:重新启动。
清空之前的所有页面在小程序中有层级的限制,只能打开十个页面,因此要合理利用跳转的方式。
2种方式。
1、默认的(在mpvue中没有继续延用vue路由的写法,而是继承小程序的一套解决方案)
var url = '/pages/counter/main'
wx.navigateTo({url})
传参数:
var url = '/pages/counter/main?id=' + this.option
wx.navigateTo({url})
2、采用vue 方式(推荐)
需要安装插件支持vue 写法
附上链接: https://github.com/F-loat/mpvue-router-patch
例如:重启时设置 reLaunch: true
可以跳转了!
this.$router.push({path:'/pages/index/main',reLaunch: true})
切换tab时只需要设置switchTab为true
this.$router.push({path:'/pages/index/main',switchTab: true})
网络请求
ajax 是存在兼容问题的,小程序是采用 flyio 跟着教程安装,然后:
1、在main.js引用并挂载
Vue.prototype.apiManager = apiManager;
2、之后在页面中就可以这样使用
this.apiManager.post
storage
由于登录功能是有效期的。有时需要我们做一下处理:(这是网上的一段代码,我还没验证过)。
export const CacheUtil = {
getStorage(key){
let data = wx.getStorageSync(key);
if (!data) {
return null;
}else{
let now = new Date().getTime()
if (now >= parseInt(data.expired)) {
wx.removeStorageSync(key)
return null;
}else{
return data.data;
}
}
return
},
setStorage(key,data,expired){
let time = new Date().getTime() + expired;
wx.setStorageSync(key,{data:data,expired:time})
},
removeStorage(key){
wx.removeStorageSync(key)
}
}
补充:
mpvue 默认是没有的,需要支持 less 语法的同学请安装:
npm i less less-loader --save
新添加目录或文件时,如果小程序不成功创建:
1、删除 工程的 package-lock.json
2、npm run dev 和 小程序开发工具重启一下