[develop native applications using weex and Vue] 5 using vuex

Time:2020-1-19

The contents of the series are here

What is vuex?

Official vuex documentation

Vuex is developed specifically for vue.js applicationsState management mode。 It uses centralized storage to manage the state of all components of the application, and ensures that the state changes in a predictable way with corresponding rules.

The core work of vuex is state management, which mainly includesState, View ActionsThese three parts constitute a simple “single data flow” to avoid data inconsistency caused by management of multiple states.

[develop native applications using weex and Vue] 5 using vuex

Vuex is a state management library specially designed for vue.js. It adapts to the data update characteristics of Vue itself, and can use the fine-grained data response mechanism of vue.js to carry out efficient state update. And it can be provided in the form of plug-in. After installation, it is very convenient to get the global state in the vuecomponent instance. The relationship and operation between modules are shown in the following figure:

[develop native applications using weex and Vue] 5 using vuex

  • State: a single state tree for the application. Generally, only one state is saved in an application (components can still keep local state), so as to facilitate state synchronization among multiple components. The update of the state will trigger the re rendering of the specified component.

  • Action: describes the action triggered by the component. It can becommitproducemutation, is the encapsulation of logic. Components only need to dispatch actions without caring about how the data is updated.

  • Mutations: describes how the status should be updated. Only submitmutationIt is the encapsulation of data operation and defines how to update status data.

The above is just an overview of vuex. To understand the detailed principle and usage, you need to see the official documents.

How to use vuex in weex

Vuex is a state management library, which uses JavaScript’s own syntax features and is platform independent, so it can be fully used in weex.

However, because the vue.js framework code has been integrated into the weexsdk (above 0.9.5), you do not need to introduce Vue again. In addition, because vuex will automatically register in the browser environment, you only need to register the vuex plug-in in a non web environment. If you repeatedly register, a warning will be thrown. The code to introduce vuex is as follows:

// import Vue from 'vue'
import Vuex from 'vuex'

// Vuex is auto installed on the web
if (WXEnvironment.platform !== 'Web') {
  Vue.use(Vuex)
}

After successful registration,All the features of vuex can be used in weex!The specific usage shall be subject to the official documents.

Examples of using vuex

Create Store

The first step is to create a globally unique store object, which contains a unique state tree and some operations.

const store = new Vuex.Store({
  state: {
    count: 0
  },

  mutations: {
    increment (state) {
      state.count++
    }
  }
})

exceptstateandmutationsIn addition, you can also transfer inactionsgettersmodulesThe relation of these attributes corresponds to the graph above one by one. Refer to its API documentation for more detailed usage. There is also a more complex example in Src / store / index.js of the weex hackernews project.

Then, when creating an instance, pass in thestoreObject, so that the store and the components are connected, and each component can use thethis.$storeTo get the status and operation in the store.

import App from 'path/to/App.vue'
import store from 'path/to/store.js'

App.el = '#root'
App.store = store

new Vue(App)

Add actions and rotations

You can’t just have data. You have to define itBehavior that triggers data modification(actions) andOperation on data(Mutations)。 Take loading user data in weex hackernews as an example, which can be simplified into the following code:

//Interface to network operations
import { fetchUser } from './fetch'

const store = new Vuex.Store({
  state: {
    users: {},
  },

  actions: {
    FETCH_USER ({ commit }, { id }) {
      //Get the new user data and submit it to mutation
      return fetchUser(id).then(user => commit('SET_USER', { user }))
    }
  },

  mutations: {
    SET_USER (state, { user }) {
      //Modify data in users and trigger interface update
      Vue.set(state.users, user.id, user)
    }
  }
})

In the code above,stateThere is one in it.userObject, all the places that need user data will be obtained from this variable, and all the changes to user data are actually the changed variable. This is the meaning of the global unique state.

And then it’s defined in the codeFETCH_USERAndSET_USERPay attention to the difference between the two. True revisionuserThe data is set ﹣ user, which is the only station that can modify the data in the state. Fetch  user is responsible for getting new data and dispatching the mutation, which callsfetchUserGet the user data, and then “submit” the new data to set user, and then perform the data update operation in the mutation,Vue.setThis method triggers the updatestate.usersThe interface element bound in.

Using Getters

Getters official document

Getters are similar to thecomputedProperty, you can do the operation according to the existing basic state, and then return a new value. It is a kind of inert evaluation to write the value taking process as getter, which also reduces the burden of state synchronization.

For example, if you want to render a group of data in a list, and you want to render the total of this group of data, if you add a “data total” attribute, you have to manually update the “data total” attribute after the list is updated, which is troublesome and error prone. In this case, it is suitable to write a getter.

const store = new Vuex.Store({
  state: {
    lists: [
      { count: 4 },
      { count: 8 },
      { count: 3 },
      { count: 9 }
    ],
  },

  getters: {
    summary ({ lists }) {
      return lists.reduce((sum, curr) => sum + curr.count, 0)
    }
  }
})

In the code abovesummaryIt’s a yeslistsGetter for array sum. In practical use, components can bethis.$store.state.listsObtainlistsList data, you can usethis.$store.getters.summaryGet the total data. The total data will be automatically updated when the list is updated.

Practical application scenarios in the project

It is defined in the Src / store / index.js file of the project of weex hackernewsactiveIdsGetter, which is used to get the data ID to be displayed in the current first screen feed list. And then it definesactiveItems, in which there are callsactiveIds, the corresponding data object will be obtained according to the active ID.

{
  //...

  getters: {
    // ids of the items that should be currently displayed based on
    // current list type and current pagination
    activeIds (state) {
      const { activeType, lists, counts } = state
      return activeType ? lists[activeType].slice(0, counts[activeType]) : []
    },

    // items that should be currently displayed.
    // this Array may not be fully fetched.
    activeItems (state, getters) {
      return getters.activeIds.map(id => state.items[id]).filter(_ => _)
    }
  }
}

Then in Src / views / storiesview.vue, acomputedProperty to get the data that the list needs to display from the store.

{
  //...

  computed: {
    stories () {
      return this.$store.getters.activeItems
    }
  }
}

In the template of storiesview.vuestoriesThis data loop is created<story>Component.

<list>
  <cell v-for="story in stories" :key="story.id">
    <story :story="story"></story>
  </cell>
</list>

Best practices?

The following are all personal opinions.

Vuex is derived from the flux architecture, which is used to manage the application state, emphasizing one-way data flow and global unique state. It can play a very important role in the application of complex data state and top-down component. The update of status can be simplified tonextState = f(state, action), there is a sense of function, which can save logic.

Although vuex is not coupled with other technologies, it is usually used in single page applications (SPA) and often used with Vue router. However, I said in the article “write independent page using weex and Vue to develop native application” 2 that the instance of weex corresponds to the concept of “browser tab” on the web. Generally, a weex instance is a “page”, that is to say, the design of weex is a “multi page application”, which is a multi instance. Using vuex in weex, its scope is instance level, and different pages (instances) cannot share state through vuex.

After all, weex renders a native interface. Although it is syntactically close to the web, it is closer to native in some basic concepts. The concepts of “single page application” and “one-way data flow” are mainly popular in the front-end. Weex is only an SDK. When developing native applications, page Jump strategies and other issues should be based on the client’s own architecture design.

Weex hackernews is a project to verify the possibility of vuex and Vue router access, not necessarily the best practice.

I don’t think weex is suitable for single page applications since it has multiple instances on the native side. Even for a relatively independent state management library like vuex, under the premise that “different pages are different instances of weex”, it needs to be based on the technical characteristics of the app itself,
Consider again whether it should be used.

For single page applications, there will be more discussion in using Vue router.

Recommended Today

PHP realizes UnionPay business H5 payment

UnionPay business H5 payment interface document: document address 1: H5 payment interface address: 1: Alipay payment Test address: http://58.247.0.18:29015/v1/netpay/trade/h5-pay Official address: https://api-mop.chinaums.com/ 2: UnionPay payment Test address: http://58.247.0.18:29015/v1/netpay/uac/order Official address: https://api-mop.chinaums.com/ 2: Basic parameters required by the interface The interface uses get parameters. After the interface parameters are directly put into the interface address, the […]