The knowledge base you need to update for Vuex2.0 of Vue. js2.0

Source: Internet
Author: User
The application structure of the knowledge base to be updated for Vue. js2.0 Vuex2.0

In fact, Vuex has no restrictions on how to organize your code structure. On the contrary, it enforces a series of advanced principles:

1. application-level statuses are concentrated in the store.

2. The only way to change the status is to commit mutations, which is a synchronous transaction.

3. asynchronous logic should be encapsulated in action.

As long as you follow these rules, it is up to you to build the structure of your project. If your store file is very large, you just need to split it into action, mutation, and getter files.

For applications that are slightly complex, we may all need to use modules. The following is a simple project architecture:

── Index.html
── Main. js
── Api
│ ──... # Initiate an API request here
── Components
│ ── App. vue
│ ──...
── Store
── Index. js # combination of modules and export store
├ ── Actions. js # root action
├ ── Mutations. js # Root mutations
── Modules
── Cart. js # cart Module
── Products. js # products Module

For more information, see the shopping cart instance.

Modules

Because a single State Tree is used, all states of an application are included in a large object. However, as our application grows, the Store becomes very bloated.

To solve this problem, Vuex allows us to split the store into modules ). Each module contains its own status, mutation, action, and getter, and even nested modules. The following is how it is organized:

const moduleA = { state: { ... }, mutations: { ... }, actions: { ... }, getters: { ... }} const moduleB = { state: { ... }, mutations: { ... }, actions: { ... }} const store = new Vuex.Store({ modules: { a: moduleA, b: moduleB }}) store.state.a // -> moduleA's statestore.state.b // -> moduleB's state

Module local status

The first receiving parameter of the mutations and getters methods of the module is the local status of the module.

Const moduleA = {state: {count: 0}, mutations: {increment: (state) {// state is the local state of the module. State. count ++ }}, getters: {doubleCount (state) {return state. count * 2 }}}

Similarly, in the module's actions, context. state exposes the local state, while context. rootState exposes the root state.

const moduleA = { // ... actions: { incrementIfOdd ({ state, commit }) {  if (state.count % 2 === 1) {  commit('increment')  } } }}

In the getters module, the root status is also exposed as the third parameter.

const moduleA = { // ... getters: { sumWithRootCount (state, getters, rootState) {  return state.count + rootState.count } }}

Namespace

Note that actions, mutations, and getters in the module are still registered in the global namespace-this will allow multiple modules to respond to the same mutation/action type. You can add a prefix or suffix to the module name to set the namespace to avoid name conflicts. If your Vuex module is reusable and the execution environment is unknown, you should do so. Distance, we want to create a todos module:

// Types. js // defines the constant names of getter, action, and mutation. // Add the 'todos 'prefix to the module name, export const DONE_COUNT = 'todos/DONE_COUNT' export const FETCH_ALL = 'todos/ FETCH_ALL 'export const TOGGLE_DONE = 'todos/toggle_done' // modules/todos. jsimport * as types from '.. /types '// define getters, actions and mutationsconst todosModule = {state: {todos: []}, getters: {[types. DONE_COUNT] (state ){//...}}, actions: {[types. FETCH_ALL] (context, payload ){//...}}, mutations: {[types. TOGGLE_DONE] (state, payload ){//...}}}

Register dynamic modules

You can use the store. registerModule method to register a module after the store is created:

store.registerModule('myModule', { // ...})

The module's store. state. myModule is exposed as the module's state.

Other Vue plug-ins can append a module to the application store, and then use the Vuex status management function through dynamic registration. For example, the vuex-router-sync library integrates vue-router and vuex by managing the application Routing Status in a dynamically registered module.

You can also use store. unregisterModule (moduleName) to remove dynamically registered modules. However, you cannot use this method to remove static modules (that is, the modules declared during store creation ).

Plugins

The Vuex store receives the plugins option, which exposes the hook for each mutation. A Vuex plug-in is a simple method that receives sotre as a unique parameter:

Const myPlugin = store =>{// the store is called when the store is initialized. subscribe (mutation, state) =>{ // The format of mutation called after mutation is {type, payload }. })}

Then use it like this:

const store = new Vuex.Store({ // ... plugins: [myPlugin]})

Submit Mutations in the plug-in

Ins cannot directly modify the status-just like your components, they can only be mutations to trigger changes.

By submitting mutations, the plug-in can be used to synchronize data sources to the store. For example, to synchronize the websocket data source to store (this is just an example of usage. In practice, the createPlugin method attaches more options to complete complex tasks ).

export default function createWebSocketPlugin (socket) { return store => { socket.on('data', data => {  store.commit('receiveData', data) }) store.subscribe(mutation => {  if (mutation.type === 'UPDATE_DATA') {  socket.emit('update', mutation.payload)  } }) }}

const plugin = createWebSocketPlugin(socket) const store = new Vuex.Store({ state, mutations, plugins: [plugin]})

Status snapshot generation

Sometimes the plug-in wants to get the status "snapshot" and the changes before and after the status changes. To implement these functions, you need to make a deep copy of The State object:

Const myPluginWithSnapshot = store => {let prevState = _. cloneDeep (store. state) store. subscribe (mutation, state) => {let nextState = _. cloneDeep (state) // compare prevState and nextState... // save the state for the next mutation prevState = nextState })}

** The agent that generates status snapshots can only be used in the development stage. Use Webpack or Browserify to let the build tool help us solve the problem:

const store = new Vuex.Store({ // ... plugins: process.env.NODE_ENV !== 'production' ? [myPluginWithSnapshot] : []})

The plug-in is used by default. To publish a product, you need to use DefinePlugin of Webpack or envify of Browserify to convert process. env. NODE_ENV! = The value of 'production 'is false.

Built-in Logger plug-in

If you are using vue-devtools, you may not need it.

Vuex brings a log plug-in for general debugging:

import createLogger from 'vuex/dist/logger' const store = new Vuex.Store({ plugins: [createLogger()]})

The createLogger method has several configuration items:

Const logger = createLogger ({collapsed: false, // automatically expand the record mutation transformer (state) {// convert the record before it starts. // For example, only return the specified subtree return state. subTree}, mutationTransformer (mutation) {// mutation format {type, payload} // We Can format return mutation as needed. type }})

The log plug-in can also directly use the script label, and then it provides the global method createVuexLogger.

Note that the logger plug-in generates status snapshots, so they are only used in the development environment.

Strict Mode

To enable strict mode, simply pass strict: true when creating the Vuex store.

const store = new Vuex.Store({ // ... strict: true})

In strict mode, an error is thrown if the Vuex status is modified outside the mutation method. This ensures that all status changes are explicitly tracked by the debugging tool.

Development Phase vs. Release Phase

Do not enable strict mode during the release phase! Strict mode performs In-depth monitoring on the Status tree to detect inappropriate changes-ensure that it is disabled during the release phase to avoid performance loss.
Similar to processing plug-ins, we can let the build tool handle:

const store = new Vuex.Store({ // ... strict: process.env.NODE_ENV !== 'production'})
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.