WeChat applet implements global loading data management similar to vuex through wxministore

First we open the terminal and introduce dependencies

npm install wxministore --save

Then if you are a new version of developer tools, just

npm i

Build it

If you have an old version of WeChat Developer Tools, open the details in the upper right corner, select Local Management, and check Use npm module.

Then create a store.js in the root directory. Of course, it is up to you to decide where to build it. Anyway, it will be introduced later.

Then write the code in store.js as follows

import Store from 'wxministore';

export default new Store({
    
    
  state: {
    
    
    name: "小狗狗"
  },
  methods: {
    
    
    publicfunction() {
    
    
        console.log("公共函数");
    }
  }
});

The state here is our public data. I only define a name here
and then a public function publicfunction.

Then we need to introduce the store we wrote in app.js.
Insert image description here
Here we introduce it and assign a value to the store in the object and put it in the root directory. This is actually to facilitate the introduction of app.js.
Then we go to the specific page interface to use
wxml. Reference code show as below

<view>
    <view>{
   
   { $state.name }}</view>
    <button bindtap="decrement">转变</button>
    <button bindtap="getdata">打印数据</button>
    <button bindtap="publicfunction">公共函数</button>
    <button bindtap="toChangeInto">跳转界面</button>
</view>

The js reference code is as follows

const app = getApp();
Page({
    
    
  data: {
    
    
  },
  onLoad() {
    
    
  },
  getdata() {
    
    
    console.log(app.store.getState().name);
  },
  decrement() {
    
    
      app.store.setState({
    
    
          name: "大猫猫"
      })
  },
  toChangeInto: function() {
    
    
    wx.navigateTo({
    
    
      url: '/pages/mint/mint'
    })
  }
 
})

First we need to get an app object through getApp.
Then here if we want to change the public data, we need to
read app.store.setState. There are two ways: app.store.getState() and $state.
In js, I recommend app.store.getState( ) You can run $state on the page
and you will find that the value of name successfully displays the puppy.
Insert image description here
Then we click print to trigger getdata.
We can be sure that the data reading is definitely no problem.
Insert image description here
Then we click transition to trigger decrement and
Insert image description here
you can see that the change is no problem at all.
Then
we click on the jump interface.
The page we want to jump to is just one line of code on wxml.

<text>{
   
   { $state.name }}</text>

By showing the name,
you can see that this data can be shared between different pages and even components.
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_45966674/article/details/132902929