current position:Home>Vuex getting started from 0 to 1

Vuex getting started from 0 to 1

2022-05-15 03:57:58Front end corner

Data sharing between components

Pass value from father to son

principle : Use v-bind Attribute binding .

Define nodes in subcomponents props, stay props Specifies the name of the value to be derived from the parent component by using an array in .

On the child component label of the parent component , Through static value transfer or v-bind The dynamic binding method specifies the connection with sub components props Property with the same name in and pass the value .

Be careful :

  • stay porps Attribute names in need of hump naming , stay template Use dashes to name .
  • Pass in to the subcomponent class and style Does not replace the previous... In the sub component template class and style, It will merge .

Pass from son to father

principle : Use v-on Event binding .

Use... On the child component label of the parent component v-on Bind custom events . Use $event Receive the transmitted value .

Used in child components $emit(' Custom event name ' , value ) Trigger user-defined events to transfer values .

Be careful :

  • v-on Bound events cannot be hump named , Because it will be automatically converted to all lowercase .

Sibling components pass values

principle : Use EventBus Manage the event center .

Create a single global Vue example , Call its... In the component to communicate with $on Monitoring events , call $emit Triggering event ,$off Destruction event .

shortcoming : It is easy to cause maintenance difficulties in large projects .

Vuex

Vuex Used to implement data ( State sharing ), Suitable for large-scale data sharing , It has the following advantages :

  • Centralized management data , Easy to maintain .
  • Efficient data sharing .
  • Responsive data , Keep data and pages synchronized in real time .

Other state management tools are :Flux、Redux etc. .

Vuex Basic use

1、 install

npm install vuex --save

2、 Import and use

import Vuex from 'vuex'
Vue.use(Vuex)

3、 establish store object

Vuex.store({
    
	state: {
     count: 0 }	// state Object to store the data to be shared 
})

stay vue In the example, we can use this.$store Access to the store object .

4、 take store The object is attached to Vue For instance

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

State

stay Vuex in ,state The attribute node is used to store data , Its value is an object , Each attribute in the object is the corresponding data .

For example, there are the following state node :

state: {
    
	count: 0,
	foo: 1,
	bar: [1,2,3]
}

Visit mode 1 :this.$store.state

stay vue The calculation properties in the component are accessed in the node count:

computed: {
    
	count(){
    
		return this.$store.state.count
	},
	bar(){
    
		return this.$store.state.bar
	}
}

Visit mode 2 :mapState Auxiliary function

First, in the vue Import the component into the function ,mapState Function can receive an object , And returns an object , You can assign a value to this object directly computed attribute .

import {
     mapState } from 'vuex'

-------------------------------------------

computed: mapState({
    
	count: 'count'	//  there 'count' Namely state Nodes in the count
	valueOfFoo: state => state.foo	//  You can use the arrow function 
	countPlus(state){
     return state.count++ }
})

If the component itself has its own local calculation properties , You can use the object expansion operator to deconstruct mapState Returned object , When mapState The property name and property value in the parameter object of are the same , You can pass in an array directly to replace the object .

computed: {
    
	...mapState(['count' , 'foo' , 'bar']),
	//  Component's own calculated properties 
	...
}

Mutations

store Object mutations The node is dedicated to operation modification state Objects in the . change vuex Medium store Medium state The only way is to submit mutations.

First, in the store Object definition mutations:

mutations: {
    
	addCount(state , param){
    	//  The first parameter is current store Object's state ,  The second parameter is a single value or object 
		state.count += param.step	//  modify state Medium count value 
	}
}

Commit in component mutations There are two ways , And you can pass in parameters when submitting ( load ), When there are many parameters, it should be passed in the form of an object .

Mode one :this.$store.commit(type)

//  The first parameter is mutations The corresponding function name in , Also called type , The second is the parameter to be passed in 
this.$store.commit('addCount' , {
     step: 1 })
//  or 
this.$store.commit('addCount' , 1)

Mode two :mapMutations

import {
     mapMutations } from 'vuex'

export default {
    
  // ...
  methods: {
    
    ...mapMutations([
      'increment', //  take  `this.increment()`  It maps to  `this.$store.commit('increment')`

      // `mapMutations`  Also supports loads :
      'incrementBy' //  take  `this.incrementBy(amount)`  It maps to  `this.$store.commit('incrementBy', amount)`
    ]),
    ...mapMutations({
    
      add: 'increment' //  take  `this.add()`  It maps to  `this.$store.commit('increment')`
    })
  }
}

Be careful :mutations Function operations in can only be synchronized , Asynchronous operations require the use of actions

Actions

Action Be similar to mutation, Difference is that :

  • Action Is submitted mutation, Instead of changing the state directly .
  • Action You can include any asynchronous operation .
actions: {
    
  increment ( context ) {
    
    setTimeout(() => {
    
      context.commit('increment')
    }, 1000)
  }
  //  or 
  increment ({
      commit }){
    
	setTimeout(() => {
    
      commit('increment')
    }, 1000)
  }
}

Distribute in components actions There are two ways

Mode one :this.$store.dispatch()

this.$store.dispatch('increment')

Mode two : Use mapActions

Use mapActions take actions Methods in are mapped to components methods The method in

import {
     mapActions } from 'vuex'

methods: {
    
	mapActions(['increment'])
}

Getters

Getters Don't modify state, The methods defined in it can be packaged or processed state After the data in... Is returned .

doneTodos: (state) => {
    	//  The first parameter is state
      return state.todos.filter(todo => todo.done)
    }

How to use in components and state equally .

this.$store.getters.doneTodos
import {
     mapGetters } from 'vuex'

computed: {
    
	...mapGetters(['doneTodos'])
}

Finally, there is a module (Module) The concept of , Next time I will !

copyright notice
author[Front end corner],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/131/202205111508004215.html

Random recommended