亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home WeChat Applet WeChat Development Can you use vue to write small programs?

Can you use vue to write small programs?

Jun 12, 2020 am 10:23 AM

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初始化完成
            // 注意全局只觸發(fā)一次?。?!
			console.log('App Launch')
		},
		onShow: function() {
            // app從后臺切入前臺或者啟動
            // 顯然這是判斷是否登陸過的好機會
			console.log('App Show')
		},
		onHide: function() {
            // app從前臺進入后臺
			console.log('App Hide')
		}

So the judgment method

 onShow: function() {
    //  查一下都獲取了那些權(quán)限
    wx.getSetting({
      success(res) {
        //   看看有沒有用戶信息,如果不存在,證明沒有登陸
        if (!res.authSetting["scope.userInfo"]) {
            // 關(guān)閉所有頁面,打開到應(yīng)用內(nèi)的登錄頁面
          wx.reLaunch({
            url: "/pages/authorise/index"
          });
        }
      }
    });
  },

The api related to jumping between pages of the mini program

wx.reLaunch(); // 關(guān)閉所有頁面,打開到應(yīng)用內(nèi)的某個頁面
wx.switchTab(); // 跳轉(zhuǎn)到 tabBar 頁面,并關(guān)閉其他所有非 tabBar 頁面
wx.navigateTo(); // 跳轉(zhuǎn)到某個頁面
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.

<button open-type="getUserInfo"  @getuserinfo="mpGetUserInfo" size="mini" v-if="show">授權(quán)登錄</button>
<button type="primary" size="mini" open-type="openSetting" @opensetting="reauthorize" v-else>重新授權(quán)</button>
 // 獲取到用戶信息后,調(diào)用登錄接口,如果被拒絕授權(quán),就跳轉(zhuǎn)到設(shè)置頁面
    mpGetUserInfo(result) {
      const that = this;
      // 查看是否授權(quán)
      wx.getSetting({
        success(res) {
          if (res.authSetting["scope.userInfo"]) {
            // 已經(jīng)授權(quán),可以直接調(diào)用 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 => {
                        // 登錄失敗,提示錯誤信息,重新打開授權(quán)頁面
                        if (判斷登錄失敗的條件) {
                          wx.redirectTo({
                            url: ""
                          });
                          // 登陸成功
                        } else {
                          // 保存登陸成功獲取的token
                          wx.setStorageSync("token", res.data.userinfo.token);
                          // 保存返回的被處理過的用戶信息
                          uni.setStorageSync("login", res.data.userinfo);
                          // 登陸成功 跳轉(zhuǎn)到tab首頁
                          wx.switchTab({
                            url: ""
                          });
                        }
                      });
                  }
                });
              }
            });
          } else {
            that.show = false;
          }
        }
      });
    },
    // 處理重新授權(quán)后的回調(diào)函數(shù)
    reauthorize(e) {
      if (e.detail.authSetting["scope.userInfo"]) {
        // 若二次授權(quán)成功,切換對話框的顯示按鈕
        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


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 &#39;axios&#39;
// 配置請求的根路徑
// 這個baseURL如果配置了跨域代理,就把proxy里配的名字給它就成
axios.defaults.baseURL = &#39;/api&#39;
// 配置請求攔截器
axios.interceptors.request.use(config => {
 // 這里做各種預(yù)處理,加token啦,攔截權(quán)限訪問啦隨便
  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: &#39;test.php&#39;, //僅為示例,并非真實的接口地址
  data: {
    x: &#39;&#39;,
    y: &#39;&#39;
  },
  header: {
    &#39;content-type&#39;: &#39;application/json&#39; // 默認(rèn)值
  },
  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: &#39;test.php&#39;, //僅為示例,并非真實的接口地址
        data: {
            x: &#39;&#39;,
            y: &#39;&#39;
        },
    header: {
        &#39;content-type&#39;: &#39;application/json&#39; // 默認(rèn)值
    },
    success (res) {
        console.log(res.data)
        }
    })
    })
}

5. Continue to encapsulate, you can’t use it directly now

// 把會改的參數(shù)抽出來,像URL啦,methods啦,data數(shù)據(jù)啦,通過形參的方式傳遞,把請求的成功或者失敗的結(jié)果弄出去
export default (params) => {
    return new Promise((resolve,reject)=>{
        wx.request({
            ...params
            header: {
                &#39;content-type&#39;: &#39;application/json&#39; // 默認(rèn)值
            },
            success (res) {
               resolve(res)   // 這里resolve出去的是res還是res.data看你們請求返回的數(shù)據(jù)
            }
            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請求的
// 比如需要設(shè)置一些字段類型 都在這里搞
export default (params) => {
    const baseUrl = "https://www.jianbingkonggu.com/"
    let head = {}
    if (判斷需要加token請求的條件) {
        head["token"] = uni.getStorageSync(&#39;token&#39;);
    }
    head[&#39;Content-Type&#39;] = &#39;application/x-www-form-urlencoded&#39;
    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(&#39;token&#39;);
    }
    head[&#39;Content-Type&#39;] = &#39;application/x-www-form-urlencoded&#39;
    return new Promise((resolve, reject) => {
        // 為了讓用戶看起來更舒服
        // 弄一個加載中動畫
        uni.showLoading({
            title: &#39;加載中&#39;
        })
        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 &#39;./utils/request&#39;
Vue.prototype.$http = Request

然后就可以開開心心在vue單文件組件里this.$http(各種參數(shù)).then()的使用拉,流暢又爽

我們還需要啥技能?用vue寫小程序

不要懷疑,山東人就是喜歡倒裝句咋地
好像沒啥了
直接

// 把之前的npm run dev:mp-weixin的黑窗口ctr+c退出哈先
// 然后執(zhí)行
npm run build:mp-weixin

關(guān)閉當(dāng)先開發(fā)者工具里的項目,重新引入dist文件夾下面的build文件夾中的mp-weixin文件夾,這是我們打包好的文件,引入之后,自己測試一遍,沒問題后點擊開發(fā)者工具的右上角上傳按鈕,進行上傳代碼,然后登錄微信小程序后臺把代碼提交審核就行啦。
以上,感謝大家,最后,關(guān)注一波我的公眾號唄,剛開始做,雖然,里面還沒放啥東西,求支持嘛。

作者:我是一個小哥哥

本文轉(zhuǎn)載自: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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
How to develop a complete Python Web application? How to develop a complete Python Web application? May 23, 2025 pm 10:39 PM

To develop a complete Python Web application, follow these steps: 1. Choose the appropriate framework, such as Django or Flask. 2. Integrate databases and use ORMs such as SQLAlchemy. 3. Design the front-end and use Vue or React. 4. Perform the test, use pytest or unittest. 5. Deploy applications, use Docker and platforms such as Heroku or AWS. Through these steps, powerful and efficient web applications can be built.

Laravel Vue.js single page application (SPA) tutorial Laravel Vue.js single page application (SPA) tutorial May 15, 2025 pm 09:54 PM

Single-page applications (SPAs) can be built using Laravel and Vue.js. 1) Define API routing and controller in Laravel to process data logic. 2) Create a componentized front-end in Vue.js to realize user interface and data interaction. 3) Configure CORS and use axios for data interaction. 4) Use VueRouter to implement routing management and improve user experience.

How to separate the front and back end of wordpress How to separate the front and back end of wordpress Apr 20, 2025 am 08:39 AM

It is not recommended to directly modify the native code when separating WordPress front and back ends, and it is more suitable for "improved separation". Use the REST API to obtain data and build a user interface using the front-end framework. Identify which functions are called through the API, which are retained on the backend, and which can be cancelled. The Headless WordPress mode allows for a more thorough separation, but it is more cost-effective and difficult to develop. Pay attention to security and performance, optimize API response speed and cache, and optimize WordPress itself. Gradually migrate functions and use version control tools to manage code.

How to push the video stream of Hikvision camera SDK to the front-end Vue project for real-time playback? How to push the video stream of Hikvision camera SDK to the front-end Vue project for real-time playback? Apr 19, 2025 pm 07:42 PM

How to push video streams from Hikvision camera SDK to front-end Vue project? During the development process, you often encounter videos that need to be captured by the camera to be circulated...

How to work and configuration of front-end routing (Vue Router, React Router)? How to work and configuration of front-end routing (Vue Router, React Router)? May 20, 2025 pm 07:18 PM

The core of the front-end routing system is to map URLs to components. VueRouter and ReactRouter realize refresh-free page switching by listening for URL changes and loading corresponding components. The configuration methods include: 1. Nested routing, allowing the nested child components in the parent component; 2. Dynamic routing, loading different components according to URL parameters; 3. Route guard, performing logic such as permission checks before and after route switching.

What is the significance of Vue's reactivity transform (experimental, then removed) and its goals? What is the significance of Vue's reactivity transform (experimental, then removed) and its goals? Jun 20, 2025 am 01:01 AM

ReactivitytransforminVue3aimedtosimplifyhandlingreactivedatabyautomaticallytrackingandmanagingreactivitywithoutrequiringmanualref()or.valueusage.Itsoughttoreduceboilerplateandimprovecodereadabilitybytreatingvariableslikeletandconstasautomaticallyreac

What are the core differences between Vue.js and React in componentized development? What are the core differences between Vue.js and React in componentized development? May 21, 2025 pm 08:39 PM

The core differences between Vue.js and React in component development are: 1) Vue.js uses template syntax and option API, while React uses JSX and functional components; 2) Vue.js uses responsive systems, React uses immutable data and virtual DOM; 3) Vue.js provides multiple life cycle hooks, while React uses more useEffect hooks.

Solve the challenges of Laravel and Vue.js form building with Composer Solve the challenges of Laravel and Vue.js form building with Composer Apr 18, 2025 am 08:12 AM

I'm having a headache when developing a project based on Laravel and Vue.js: How to create and manage forms efficiently. Especially when it is necessary to define the form structure on the backend and generate dynamic forms on the frontend, traditional methods appear cumbersome and error-prone. I tried many methods, but the results were not satisfactory. Finally, I discovered the k-eggermont/lara-vue-builder library, which not only simplified my workflow, but also greatly improved the development efficiency.

See all articles