Data read and write about Vuex

Vuex definition

Like our handwritten store, the tool used to manage data can be thought of as an object. It can help us rewrite the data.

Vuex use

const store = new Vuex.Store({
  state: {
    count:0
  },
})
console.log(store.state.count)
Copy the code

First introduce, and add data.

const store = new Vuex.Store({
  state: { // data
    count: 0
  },
  mutations: { // data
    increment (state) {
      state.count++
    }
  }
})
Copy the code

Secondly, they use mutations, the data.

Here’s the weird part.

For mutations to work, we need to trigger store.com MIT.

console.log(store.state.count)
store.commit('increment')
console.log(store.state.count)
Copy the code

The result is:

0
1
Copy the code

Live learning and use:

const store = new Vuex.Store({
  state: { // data
    count:0
  },
  mutations: {increment(state,n:number){// methods
      state.count += n
    }
  }
})
console.log(store.state.count)
store.commit('increment'.10)
console.log(store.state.count)
Copy the code

Add n, as many as you want.

The result is:

0 to 10Copy the code

state

Single state tree

state: { // data
    count:0
  },
Copy the code

Official explanation: use one object to contain the entire application hierarchy state. At this point it serves as a “unique data source.

Essence: State contains data for all components in a project in one object. It’s the only source of data.

Get the Vuex state in the component

Method 1: Use computed

Calculate attribute

 computed:{
    count(){
      return store.state.count
    }
  }
Copy the code

Use computed import. The computed properties can continue to implement the changed function. So that our data is not only executed once.

The template

<div>
   <button @click="add">+ 1</button>
   {{count}}
</div>   
Copy the code

The trigger

 add(){
    store.commit('increment'.1)}Copy the code
Method 2: Obtain it directly from the Vue instance

Open the store/index. Ts

Vue.use(Vuex)
Copy the code

Attach the store to vue.prototype

In the main. Ts

new Vue({
    router,
    store,
    render: h= > h(App)
}).$mount('#app');
Copy the code

The store will be attached to the Vue instance.

So we can use this.$store directly to get the data.

Calculate attribute

 computed:{
    count(){
      return this.$store.state.count
    }
  }
Copy the code

Template and trigger

<div>
    <button @click="$store.commit('increment',1)">+ 1</button>
    {{count}}
</div>
Copy the code