Foreword: Every day to learn a knowledge point, can reduce a line of code, so that the project is more lightweight.

With the elaboration of project components, state sharing between multiple components is frequently encountered. Vuex can be used to solve such problems. However, according to Vuex’s official website, if the application is not large enough, in order to avoid tedious and redundant code, it is better not to use Vuex. Vue.js2.6 has a vue.Observable (Object) API that replaces vuex for data state management. Using this API we can deal with some simple sharing of data state across components. Vue.observable(Object)

Observable () method, which sets monitoring properties. It monitors property changes in the View Module, dynamically changing the value of an element. The type invariant of a monitoring property is a function. To monitor the property.

Let’s see an example of how it’s used

// store.js
import Vue from 'vue'

export const state = Vue.observable({ 
  count: 0 
})
Copy the code

Using the Vue. Observables (object)

<div @click="setCount">{{ count }}</div>
Copy the code
import {state} from '.. /store.js'

export default {
    computed: {
        count() {
            return state.count
        }
    },
    methods: {
        setCount() {
            state.count++
        }
    }
}
Copy the code

It was also possible to duplicate the state change using vuEX custom mutation

import Vue from 'vue'

export const state = Vue.observable({ 
  count: 0 
})

export const mutations = {
  SET_COUNT(payload) {
    if (payload > 0) {
        state.count = payload
    } 
  }
}
Copy the code

Use:

import {state, mutations} from '.. /store.js'

export default {
    computed: {
        count() {
            return state.count
        }
    },
    methods: {
        setCount() {
            mutations.SET_COUNT(100)}}}Copy the code

Comparing the two approaches gives the same effect, but for small and medium-sized projects, vue.Observable () is sufficient for state management.

I see a long road ahead, I will search up and down, refueling together, learn the front end ~

Stuck_out_tongue_closed_eyes: