Explain the global variable implementation of uniapp in detail

  • 2021-10-18 08:15:02
  • OfStack

Preface

This article sorts out the implementation methods of uniapp global variables. The details come from the implementation of uniapp global variables in uView official website. Interested students can go to uView official website to search vuex for viewing

Implementation of global variables

1 Generally speaking, there are the following ways in uniapp

Local storage Configuration file Mount to Vue. prototype globalData vuex

The implementation of these five methods is introduced below

Local storage

Permanently stored. Take app as an example, even if the application is closed, the data will still be stored

This is a permanent storage method, Local Storage similar to web (about Cookie, Token, SessionStorage, LocalStorage, Will be organized in another article), we will use this method when we need to permanently store some 1 information of users, but we need to pay attention to avoid frequent acquisition and modification of stored data in this way, because it will have a certain impact on performance, and we should not use this method when applying variables in the declaration period

There are two kinds of storage methods: synchronous and asynchronous

Synchronous storage


  // Synchronous storage 
  uni.setStorageSync("key","value")
  // Synchronous acquisition 
  let value = uni.getStorageSync("key")  
  console.log(" I will wait until the above execution is finished before executing it )

Asynchronous storage


  uni.setStorage({
   key:"key",
    data:"value",
    success:function(){
      // Store successful callbacks 
      console.log(" I am the callback of asynchronous storage, and I will be in val Executed after declaration ")
    }
  })
  let val = 1// This line will execute first 
  
  uni.getStorage({
   key:"key",
    success:function(res){
      // Store successful callbacks 
      console.log(" I get the callback asynchronously, and I will call it in val2 Executed after declaration ")
    }
  })
  let val2 = 2// This line will execute first 

Configuration file

This is a way to use modular file export. First, write variables in js file, and then export them in the form of export default

1 Generally speaking, the global variables realized in this way are the variables that must be used before the application is installed by the user and uninstalled by the user, such as the domain name requested by the back end. Other situations are not suitable for this way, and this way also has disadvantages, that is, files need to be introduced every time it is used

config.js


  // As in config.js Medium   We exported 1 Basic domain name 
  export default{
   baseUrl:"http://www.test.com"
  }

index.js


  // Pass import Introduce this file 
  import config from "../common/config.js"
  export default {
    onLoad(){
     console.log(config.baseUrl)//baseUrl:"http://www.test.com"
    }
  }

Mount to Vue. prototype

This is an implementation method using prototype (the prototype chain and inheritance of js will be sorted out in another article), but this method will have special performance in WeChat applet

Note: In the WeChat applet, the template cannot directly read the global variables introduced by the display
main.js


  // Here's config.js Refer to the documents already written above 
  import config from "./common/config.js"
  // Will baseUrl Mount to Vue After that, you can pass the this.baseUrl The way to access 
  Vue.prototype.baseUrl = config.baseUrl

In the page


<template>
 <!--  The median value of WeChat applet is undefined The other end is valid  -->
 <view>
  Values are: {{this.baseUrl}}
 </view>
</template>

<script>
 export default {
 onLoad() {
    console.log(this.baseUrl)//"http://www.test.com"
 }
 }
</script>

globalData

This method is unique to WeChat applets. Applets cannot use vuex, so globalData appears. uniapp is another implementation of applets, so globalData also appears

There are several points to note when using globalData:

globalData is not responsive. Modifications to globalData in one file will not be dynamically responded to in another file If you want to implement the "response" of globalData, you need to manually obtain the value in the life cycle of onShow

To explain point 2, why do you need to get the value onLoad in onShow?

Because if globalData is introduced into A and B pages, B modifies the value of globalData inside the page and returns to A page, then A page is not destroyed and will not call onLoad life hook, but will only execute onShow. At this time, globalData is obtained in onLoad, then it will not be executed and cannot be responsive

App.vue


  export default{
   // Need to be in App.vue To define in globalData
   globalData:{
     userName:" Bai Juyi "
    },
    // It should be noted here that if you want to App.vue Use in globalData Can not be used directly getApp().globalData.Name , because at this time getApp() Not generated 
    // 1.  Non V3 Mode, which can be passed through this.$scope.globalData Get 
   // 2. V3 Mode, which can be passed through getApp({allowDefault: true}).globalData Get 
    onLaunch(){
     console.log(this.$scope.globalData.userName)
    }
  }

When globalData is defined in App. vue, we can use it in the page
A.vue


<template>
 <view>
 <view>
  <!--  Note that you cannot use it directly in a template  getApp().globalData.userName -->
  << Charcoal seller >> The author is: {{author}}
 </view>
 <view>
  <u-button @click="modifyUserName"> Modify userName Value </u-button>
 </view>
 </view>
</template>

<script>
 export default {
 data() {
  return {
  author: ''
  }
 },
 onShow() {
  //  Every time A.vue Triggers when it appears on the screen onShow To update the author Value 
  this.author = getApp().globalData.userName;
 },
 methods: {
  modifyUserName() {
                // Modified at this time globalData Value of 
  getApp().globalData.userName = " Poet saint " ; 
  //  Modify userName After, the of this page author Still does not refresh automatically because globalData Not responsive 
  //  We still need to manually refresh the author Value, which shows that globalData The malpractice of 
  this.author = getApp().globalData.userName;
  }
 }
 }
</script>

Implementation of Vuex

It is strongly recommended to use vuex. There are two ways to use vuex in uniapp, one is based on traditional vue, and the other is encapsulated by uView. The encapsulation of vuexd by uView official website is introduced below

Traditional implementation mode

The use of traditional vuex is only briefly introduced here. If you don't know vuex, you can go to vue official website to view the official documents

Create an store file in the root directory of uni. app, and create an index. js file with the following contents


//index.js
  import Vue from "vue"
  import Vuex from "vuex"
  Vue.use(Vuex)
  const store = new Vuex.Store({
   state:{
     vuex_token:"123456"
    },
    // Synchronous modification  state  Median method 
    mutations:{
     //payload Enable users to use the mutations Is an incoming parameter, which can make a single 1 Values can also be objects 
     modifyToken(state,payload){
       state.vuex_token = payload.token
      }
    }
  })
  export default store

Introduced in main. js


import store from '@/store';

//  Will store Put in Vue Object is being created 
const app = new Vue({
 store,
 ...App
})

Use in the page


  uni.setStorage({
   key:"key",
    data:"value",
    success:function(){
      // Store successful callbacks 
      console.log(" I am the callback of asynchronous storage, and I will be in val Executed after declaration ")
    }
  })
  let val = 1// This line will execute first 
  
  uni.getStorage({
   key:"key",
    success:function(res){
      // Store successful callbacks 
      console.log(" I get the callback asynchronously, and I will call it in val2 Executed after declaration ")
    }
  })
  let val2 = 2// This line will execute first 
0

Implementation of vuex for uView (Emphasis)

There are two reasons why uView encapsulates vuex

uView feels that it is necessary to define state and mutations in vuex, and introduce mapState for deconstruction in every place where vuex is needed, and then use it again (cumbersome operation) Because vuex stores variables in memory, refreshing the browser will cause vuex variables to disappear, and it needs to be used with other storage methods such as LocalStorage

In view of these problems, uView officially provides a set of methods for encapsulating and using vuex. This method combines LocalStorage and vuex, so that users don't have to call vuex tediously and consider the problem of refreshing loss. I will show the code below, and explain its ideas and process

First, create an index. js file under the root directory, write the following contents, I will provide general ideas at the beginning, and explain the specific meaning in the comments later

Idea: The general idea of index. js is as follows

a. In order to solve the problem that vuex refresh loss can not store data permanently, create an lifeData object, this object will be stored in LocalStorage through the function, in order to achieve the effect of permanent storage, at this time I only need to store the data in vuex permanently in the form of key, value in this object

b. In order to solve the problem that every time we use vuex, we need to use the functions in mutations to operate the corresponding variables in stroe. We encapsulate the method of $uStore to operate all the variables in store. Of course, only a simple copy operation is carried out. For more expanded functions, users can encapsulate the functions in mutations to expand

c. Encapsulates an saveStateKeys array, The data of this array will be fetched when app starts, Therefore, we can put some data that needs to be obtained when app is started. For example, the information that the user has logged in last time in the application, in fact, saveStateKeys and lifeData are used together. Only the variables in saveStateKeys will be stored in lifeData to achieve permanent storage, while others are stored in the same way as ordinary vuex. For this point, we can see in the following code


  uni.setStorage({
   key:"key",
    data:"value",
    success:function(){
      // Store successful callbacks 
      console.log(" I am the callback of asynchronous storage, and I will be in val Executed after declaration ")
    }
  })
  let val = 1// This line will execute first 
  
  uni.getStorage({
   key:"key",
    success:function(res){
      // Store successful callbacks 
      console.log(" I get the callback asynchronously, and I will call it in val2 Executed after declaration ")
    }
  })
  let val2 = 2// This line will execute first 
1

Create the mixin. js file in the same directory

Thoughts:
a. In order to be able to use variables on every page through this., we need to blend mapState globally through Vue mixin
b. In order to easily call mutations in vuex on every page, we need a method that can help us call uStore instead of using commit every time, so uView is mixed with another method $u. vuex

ps: minxi is a kind of api provided by Vue to realize global function. There are many ways of mixing. Global mixing is used here. If you don't know much about mixing, you can go to Vue official website to view relevant documents


  uni.setStorage({
   key:"key",
    data:"value",
    success:function(){
      // Store successful callbacks 
      console.log(" I am the callback of asynchronous storage, and I will be in val Executed after declaration ")
    }
  })
  let val = 1// This line will execute first 
  
  uni.getStorage({
   key:"key",
    success:function(res){
      // Store successful callbacks 
      console.log(" I get the callback asynchronously, and I will call it in val2 Executed after declaration ")
    }
  })
  let val2 = 2// This line will execute first 
2

Start global blending, and introduce mixin. js file in main. js for blending


//main.js
let vuexStore = require("@/store/$u.mixin.js");
Vue.mixin(vuexStore);

Put store into an Vue instance


  uni.setStorage({
   key:"key",
    data:"value",
    success:function(){
      // Store successful callbacks 
      console.log(" I am the callback of asynchronous storage, and I will be in val Executed after declaration ")
    }
  })
  let val = 1// This line will execute first 
  
  uni.getStorage({
   key:"key",
    success:function(res){
      // Store successful callbacks 
      console.log(" I get the callback asynchronously, and I will call it in val2 Executed after declaration ")
    }
  })
  let val2 = 2// This line will execute first 
4

The above is the official encapsulation of vuex by uView. It is very convenient to use this encapsulated vuex in the development of app. At the same time, you can expand your own methods in @/stote/index.js as needed

Conclusion

These are the different implementations of uniapp global variables. The specific use of which one needs to be selected according to the actual development. Personally, I feel that the encapsulation of vuex by uView has a high reference value for me when I first entered the front end, so I specially sorted it out and kept it for sharing.


Related articles: