Home>Article>WeChat Applet> Can you use vue to write small programs?
1. Login authorization
1. Mini program login mechanism
Traditional login (jwt method as an example)
The user enters the username and password (the password needs to be encrypted through certain algorithms) to access the login interface
The backend verifies the username and password, encrypts the user's information into a token string, and returns it to the frontend
The frontend saves the token (locally) Storage, here involves an interview question: What is the difference between localstorage, sessionstorage, and cookie? Ask yourself)
Every time the front-end sends a request, it sends the token to the back-end. , it is up to the backend to determine whether the login status is legal (how to pass the token, whether to put it in the header or in the body, discuss it with the backend yourself)
Then the front-end determines whether to execute something based on the return situation Operation
Mini program login authorization The mini program does not have a login box, but only authorizes the use of user information. What is the process like? The simple steps are: Obtain user information for authorization----->Call wx.login interface------>Get the returned unique identity authentication code----->pass the code to you with user information Backend----->The back end is the same as above
It should be noted that the
code can only be used once. And it expires in five minutes. If it expires, you need to wx.login() again
2. We do login authorization
##2-1 , Thinking scenario
Before loading the mini program, determine whether you have logged in (that is, whether you have a token). If you have not logged in, jump to the login interface (or directly call to obtain user information) Interface and login interface
2-2 Determination before login
Before loading the mini program, determine whether to log in , and make the corresponding jump How to judge before loading?------>Life cycle hook function At this time, when we open App.vue in the project, we will see the following Code:onLaunch: function() { // 这时app初始化完成 // 注意全局只触发一次!!! console.log('App Launch') }, onShow: function() { // app从后台切入前台或者启动 // 显然这是判断是否登陆过的好机会 console.log('App Show') }, onHide: function() { // app从前台进入后台 console.log('App Hide') }
So the judgment method
onShow: function() { // 查一下都获取了那些权限 wx.getSetting({ success(res) { // 看看有没有用户信息,如果不存在,证明没有登陆 if (!res.authSetting["scope.userInfo"]) { // 关闭所有页面,打开到应用内的登录页面 wx.reLaunch({ url: "/pages/authorise/index" }); } } }); },
The api related to jumping between pages of the mini program
wx.reLaunch(); // 关闭所有页面,打开到应用内的某个页面 wx.switchTab(); // 跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面 wx.navigateTo(); // 跳转到某个页面 wx.navigateBack(); // 返回到上个页面,需要跟navigateTo配合使用Please refer to the wx documentation for specific usage. If you really can’t stand it, just look at the uniapp documentation. They look the same anyway. Uniapp’s api package inherits the mini program’s api. Basically, the mini program’s api is the same as wx in front of it. You can use it if you change the word to uni
2-3. Login operation
Not much to say, just look at some of the codes on WeChat The permissions API has been abandoned. Now you can only perform some permission operations through the button's opentype attribute. The following code includes handling the secondary boot authorization login process after the user refuses authorization.// 获取到用户信息后,调用登录接口,如果被拒绝授权,就跳转到设置页面 mpGetUserInfo(result) { const that = this; // 查看是否授权 wx.getSetting({ success(res) { if (res.authSetting["scope.userInfo"]) { // 已经授权,可以直接调用 getUserInfo 获取头像昵称 wx.getUserInfo({ success: function(res) { that.userInfo = res.userInfo; wx.login({ success: function(loginRes) { that.userInfo.code = loginRes.code; that.$http({ url: "登录接口地址", data: that.userInfo, method: "POST" }) .then(res => { // 登录失败,提示错误信息,重新打开授权页面 if (判断登录失败的条件) { wx.redirectTo({ url: "" }); // 登陆成功 } else { // 保存登陆成功获取的token wx.setStorageSync("token", res.data.userinfo.token); // 保存返回的被处理过的用户信息 uni.setStorageSync("login", res.data.userinfo); // 登陆成功 跳转到tab首页 wx.switchTab({ url: "" }); } }); } }); } }); } else { that.show = false; } } }); }, // 处理重新授权后的回调函数 reauthorize(e) { if (e.detail.authSetting["scope.userInfo"]) { // 若二次授权成功,切换对话框的显示按钮 this.show = true; } }In this way, it's done. As for What is this.$http? Please read the third article (I haven’t written it yet, why?) After reading it, please give it a like. If you continue reading, let me make a complaint first. It’s been three days and I haven’t received it yet. Salary, so annoying, let’s fish together, friends
I mentioned it in my last reply
1. Send a request in the PC-side vue project
Foolish steps: (Use axios)yarn add axios // npm 也行啦
// 在cli项目中 // main.js中 import axios from 'axios' // 配置请求的根路径 // 这个baseURL如果配置了跨域代理,就把proxy里配的名字给它就成 axios.defaults.baseURL = '/api' // 配置请求拦截器 axios.interceptors.request.use(config => { // 这里做各种预处理,加token啦,拦截权限访问啦随便 return config }, (error) => { return Promise.reject(error) }) axios.interceptors.response.use(config => { return config }) // 挂载到vue上 Vue.prototype.$http = axios
2. Mini program request1. Native approach:
wx.request({ url: 'test.php', //仅为示例,并非真实的接口地址 data: { x: '', y: '' }, header: { 'content-type': 'application/json' // 默认值 }, success (res) { console.log(res.data) } })xue Wei is a little uncomfortable because he is used to axios and supports promises, so we will let him Support promises 2. Encapsulate a small request function that supports promises 1. Create a new request.js file and put it in a folder called utils (I won’t tell you What does utils mean) 2. Export a default function object 3. The function returns a promise, which contains a resolve and a reject. If you don’t know what a promise is, please read my other articles
export default () => { return new Promise((resolve,reject)=>{ }) }4. Encapsulate WeChat’s api (uniapp’s api will also work. If there is a cross-end requirement, just encapsulate uni’s requestapi directly, which is almost the same)
export default () => { return new Promise((resolve,reject)=>{ wx.request({ url: 'test.php', //仅为示例,并非真实的接口地址 data: { x: '', y: '' }, header: { 'content-type': 'application/json' // 默认值 }, success (res) { console.log(res.data) } }) }) }5. Continue to encapsulate, you can’t use it directly now
// 把会改的参数抽出来,像URL啦,methods啦,data数据啦,通过形参的方式传递,把请求的成功或者失败的结果弄出去 export default (params) => { return new Promise((resolve,reject)=>{ wx.request({ ...params header: { 'content-type': 'application/json' // 默认值 }, success (res) { resolve(res) // 这里resolve出去的是res还是res.data看你们请求返回的数据 } fail: (err) => { reject(err) }, ) }) }6. Axios has a baseURL to save effort, we also have to have
export default (params) => { const baseUrl = "写你自己的地址的公共部分" return new Promise((resolve, reject) => { wx.request({ ...params, url: baseUrl + params.url, success: (res) => { resolve(res.data) }, fail: (err) => { reject(err) } }); }) }7. Process the request header
// 比如需要携带token请求的 // 比如需要设置一些字段类型 都在这里搞 export default (params) => { const baseUrl = "https://www.jianbingkonggu.com/" let head = {} if (判断需要加token请求的条件) { head["token"] = uni.getStorageSync('token'); } head['Content-Type'] = 'application/x-www-form-urlencoded' return new Promise((resolve, reject) => { wx.request({ ...params, url: baseUrl + params.url, header: head, success: (res) => { resolve(res.data) }, fail: (err) => { reject(err) } }); }) }
Full version
export default (params) => { const baseUrl = "https://www.jianbingkonggu.com/" let head = {} if (!params.url.includes("/MiniProgramLogin")) { head["token"] = uni.getStorageSync('token'); } head['Content-Type'] = 'application/x-www-form-urlencoded' return new Promise((resolve, reject) => { // 为了让用户看起来更舒服 // 弄一个加载中动画 uni.showLoading({ title: '加载中' }) wx.request({ ...params, url: baseUrl + params.url, header: head, success: (res) => { resolve(res.data) }, fail: (err) => { reject(err) }, complete: () => { // 请求完成 // 隐藏加载中的提示框 uni.hideLoading() } }); }) }
2. How to use it in the project?
In one sentence, it’s the same as axios挂载
使用
在main.js里
import Request from './utils/request' Vue.prototype.$http = Request
然后就可以开开心心在vue单文件组件里this.$http(各种参数).then()的使用拉,流畅又爽
我们还需要啥技能?用vue写小程序
不要怀疑,山东人就是喜欢倒装句咋地
好像没啥了
直接
// 把之前的npm run dev:mp-weixin的黑窗口ctr+c退出哈先 // 然后执行 npm run build:mp-weixin
关闭当先开发者工具里的项目,重新引入dist文件夹下面的build文件夹中的mp-weixin文件夹,这是我们打包好的文件,引入之后,自己测试一遍,没问题后点击开发者工具的右上角上传按钮,进行上传代码,然后登录微信小程序后台把代码提交审核就行啦。
以上,感谢大家,最后,关注一波我的公众号呗,刚开始做,虽然,里面还没放啥东西,求支持嘛。
作者:我是一个小哥哥
本文转载自:https://juejin.cn/user/131597127388024/posts
推荐教程:《微信小程序》
The above is the detailed content of Can you use vue to write small programs?. For more information, please follow other related articles on the PHP Chinese website!