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 jumpHow to judge before loading?------>Life cycle hook functionAt 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配合使用
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.<button open-type="getUserInfo" @getuserinfo="mpGetUserInfo" size="mini" v-if="show">授权登录</button> <button type="primary" size="mini" open-type="openSetting" @opensetting="reauthorize" v-else>重新授权</button>
// 获取到用户信息后,调用登录接口,如果被拒绝授权,就跳转到设置页面 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; } }
I mentioned it in my last reply
This.$http sends a request, what is this?
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) } })
export default () => { return new Promise((resolve,reject)=>{ }) }
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) } }) }) }
// 把会改的参数抽出来,像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) }, ) }) }
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) } }); }) }
// 比如需要携带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- Introduction
挂载
使用
在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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

There are three ways to refer to JS files in Vue.js: directly specify the path using the <script> tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses <router-link to="/" component window.history.back(), and the method selection depends on the scene.

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the <script> tag in the HTML file that refers to the Vue file.

There are two main ways to pass parameters to Vue.js functions: pass data using slots or bind a function with bind, and provide parameters: pass parameters using slots: pass data in component templates, accessed within components and used as parameters of the function. Pass parameters using bind binding: bind function in Vue.js instance and provide function parameters.
