Home  >  Article  >  Web Front-end  >  uniapp hybrid development implements login function

uniapp hybrid development implements login function

WBOY
WBOYOriginal
2023-05-26 10:02:361400browse

With the popularity of mobile devices, mobile applications have become an indispensable part of people's daily lives. Implementing the login function is one of the basic functions of any application. In this article, we will introduce how to use the uniapp hybrid development framework to implement the login function.

1. Introduction to uniapp

Uniapp is a hybrid development framework based on Vue.js. It can use the same set of code to develop applications for multiple platforms such as iOS, Android, H5, and small programs. . More importantly, it also supports local packaging and cloud packaging functions, which can greatly improve application development efficiency and user experience.

2. Implementation process

The process of implementing the login function is roughly as follows:

  1. Write the login interface, including user name and password input boxes, and login buttons.
  2. Manage the user's login status in uniapp's vuex (Vue.js status manager).
  3. Pass the user's login information to the server for verification through a network request.
  4. After successful verification, store the user's relevant information in the local cache and update the user status in vuex.
  5. Determine whether the user is logged in in the application to implement related functions.

Next, we will implement the above process step by step.

2.1 Write the login interface

In the uniapp project, the interface is implemented by writing Vue components. We create the Login.vue file in the pages folder, and write the code for the login interface as follows:

<!-- Login.vue -->
<template>
  <view class="container">
    <view class="input-box">
      <input v-model="username" type="text" placeholder="用户名">
    </view>
    <view class="input-box">
      <input v-model="password" type="password" placeholder="密码">
    </view>
    <view class="btn-wrapper">
      <button @click="handleLogin">登录</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    handleLogin() {
      /* 登录验证 */
    }
  }
}
</script>

<style>
/* 样式 */
</style>

In the above code, we use the Vue component provided by uniapp and some simple styles to build the login interface. We define the input box and login button, and call the handleLogin method when the login button is clicked.

2.2 Managing user status

In uniapp, the tool for managing application status is vuex. You need to first create a store folder in the project (if it does not exist) and create the index.js file under the store folder. Next, we define the user's status and operations in index.js:

// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    userInfo: null, // 用户信息
    isLogin: false // 是否登录
  },
  mutations: {
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    setIsLogin(state, isLogin) {
      state.isLogin = isLogin
    }
  },
  actions: {
    login({ commit }, userInfo) {
      /* 登录验证 */
    },
    logout({ commit }) {
      /* 退出登录 */
    }
  }
})

export default store

In the above code, we first use the Vuex plug-in through the Vue.use() method, and then define the store object. In the store object, we use the basic concepts of Vue.js such as state, mutations, and actions. State is used to save the state of the application, mutations are used to modify the state, and actions are used to submit mutations. We have defined two states: userInfo and isLogin, which are used to save user information and whether the user is logged in respectively. Next, we define two operations: login and logout. These operations are modifications and submissions to the state.

2.3 Perform login verification

Next, we need to implement login verification logic. In actions, we define the login method. In this method we can perform an asynchronous operation in order to request the server for verification.

// store/index.js
actions: {
  async login({ commit }, userInfo) {
    const res = await uni.request({
      url: 'http://api.example.com/login',
      method: 'POST',
      data: userInfo
    })

    if(res.data.code === 0) {
      // 登录成功
      const userInfo = res.data.userInfo

      // 更新本地存储信息
      uni.setStorageSync('userInfo', userInfo)

      // 更新Vuex状态
      commit('setUserInfo', userInfo) // 存储用户信息
      commit('setIsLogin', true) // 修改登录状态
    } else {
      // 登录失败
      uni.showToast({
        title: '登录失败',
        icon: 'none'
      })
    }
  }
}

In the login method, we first send a POST request to the server through the uni.request method and pass the user information over. After receiving feedback from the server, we made a simple judgment. If the login verification passes, the user information returned by the server is stored in the local cache, and the user information and login status in vuex are updated. If the verification fails, a prompt message will pop up.

2.4 Logout

In the store/index.js file, we also define the logout method to handle the user's logout behavior:

// store/index.js
actions: {
  // ...省略上文中的代码
  async logout({ commit }) {
    // 清除本地缓存信息
    uni.removeStorageSync('userInfo')

    // 清除App Store
    commit('setUserInfo', null)
    commit('setIsLogin', false)
  }
}

In the logout method, We can use the uni.removeStorageSync method to clear local cache information. At the same time, the user information and login status in vuex also need to be updated.

2.5 Determining the user login status in the application

In the application, it is necessary to determine whether the user is logged in. If you are not logged in, you need to jump to the login page. We use the global routing hook beforeEach in Vue.js to determine whether to log in. The code is as follows:

// main.js
import Vue from 'vue'
import App from './App'
import store from './store'

Vue.config.productionTip = false

App.mpType = 'app'

const app = new Vue({
  store,
  ...App
})

app.$mount()

// 全局路由钩子
uni.$on('routeUpdate', function() {
  uni.getStorage({
    key: 'userInfo',
    success: function(res) {
      // 用户已登录,更新Vuex状态
      store.commit('setIsLogin', true)
      store.commit('setUserInfo', res.data)
    },
    fail: function() {
      // 用户未登录,跳转到登录页
      if(uni.getStorageSync('isLogin') !== 'true' && uni.getStorageSync('isLogin') !== true) {
        uni.navigateTo({
          url: '/pages/Login'
        })
      }
    }
  })
})

In the above code, we use the uni.$on method to listen to the update event of the route. When the route changes, judgment at the time. First, we obtain the user information in the local cache through the uni.getStorage method. If the user information is successfully obtained, it means that the user has logged in, and we can update the user status in vuex. Otherwise, it will jump to the login page.

3. Summary

In this article, we introduced how to use the uniapp hybrid development framework to implement the login function. First, we built the application interface by writing the login interface; then, we used vuex to manage the application status and record and manage the user login status; then, we verified the user login information through network requests in the application, and used Local caching technology records user status; finally, we use the routing hook mechanism to determine and jump to user login status.

The above is the detailed content of uniapp hybrid development implements login function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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