Vuex of the Vue family bucket

Vuex of the Vue family bucket

1. Vuex overview

1.1 How to share data between components

父向子传值:v-bind property binding

子向父传值:v-on event binding

兄弟组件之间共享数据: EventBus

  • $onthe component that receives the data
  • $emitthe component that sends the data

1.2 What is Vuex

VuexIt is a mechanism to realize the global state (data) management of components, which can be convenient 实现组件之间数据的共享.

insert image description here

1.3 The benefits of using Vuex to manage state uniformly

①Able to centrally manage shared data in vuex, which is easy to develop and maintain

② It can efficiently realize data sharing between components and improve development efficiency

③ The data stored in vuex is responsive and can keep the data synchronized with the page in real time

1.4 What kind of data is suitable for storing in Vuex

In general, 只有组件之间共享的数据,才有必要存储到 vuex 中for the private data in the component, it can still be stored in the data of the component itself.

2. Basic use of Vuex

1. Install vuex dependencies

npm install vuex --save

2. Import the vuex package

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

3. Create a store object

const store = new Vuex.Store({
    
    
	// state 中存放的就是全局共享的数据
	state: {
    
     count: 0 }
})

4. Mount the store object to the vue instance

new Vue({
    
    
	el: '#app', 
	render: h => h(app), 
	router, 
	// 将创建的共享数据对象,挂载到 Vue 实例中 
	// 所有的组件,就可以直接从 store 中获取全局的数据了 
	store 
})

Case: Calculator

Open the vuex project you just created, find the one in the src directory, App.vue组件and rewrite the code as follows:

<template>
  <div>
    <my-addition></my-addition>

    <p>----------------------------------------</p>

    <my-subtraction></my-subtraction>
  </div>
</template>

<script>
import Addition from './components/Addition.vue'
import Subtraction from './components/Subtraction.vue'

export default {
    
    
  data() {
    
    
    return {
    
    }
  },
  components: {
    
    
    'my-subtraction': Subtraction,
    'my-addition': Addition
  }
}
</script>

<style>
</style>

Created in the components folder Addition.vue组件, the code is as follows:

<template>
    <div>
        <h3>当前最新的count值为:</h3>
        <button>+1</button>
    </div>
</template>

<script>
export default {
  data() {
    return {}
  }
}
</script>

<style>
</style>

Created in the components folder Subtraction.vue组件, the code is as follows:

<template>
    <div>
        <h3>当前最新的count值为:</h3>
        <button>-1</button>
    </div>
</template>

<script>
export default {
    
    
  data() {
    
    
    return {
    
    }
  }
}
</script>

<style>
</style>

Finally, create a .prettierrcfile and write the code as follows:

{
    "semi":false,
    "singleQuote":true
}

insert image description here

3. Core concepts of Vuex

3.1 Overview of core concepts

The main core concepts in Vuex are as follows:

  • State
  • Mutation
  • Action
  • Getter

3.2 State

StateProvide the only public data source, and all shared data should be stored in the State of the Store.

// 创建store数据源,提供唯一公共数据
const store = new Vuex.Store({
    
    
	state: {
    
     count: 0 }
})

Component access data in State 第一种方式:

this.$store.state.全局数据名称

Component access data in State 第二种方式:

// 1. 从 vuex 中按需导入 mapState 函数
import {
    
     mapState } from 'vuex'

Through the imported mapState function, the global data required by the current component is mapped to the computed property of the current component:

// 2. 将全局数据,映射为当前组件的计算属性 
computed: {
    
     
	...mapState(['count']) 
}

3.3 Mutation

MutationUsed to change the data in the Store.

①The Store data can only be changed through mutation, and the data in the Store cannot be directly manipulated.

②In this way, although the operation is a little more cumbersome, the changes of all data can be monitored centrally.

// 定义 Mutation 
const store = new Vuex.Store({
    
     
	state: {
    
     
		count: 0 
	}, 
	mutations: {
    
     
		add(state) {
    
     
			// 变更状态 
			state.count++ 
		} 
	} 
})
// 触发mutation 
methods: {
    
     
    	handle1() {
    
     
            // 触发 mutations 的第一种方式 
            this.$store.commit('add') 
        } 
}

You can pass parameters when starting mutations:

// 定义Mutation
const store = new Vuex.Store({
    
    
	state: {
    
    
		count: 0
	},
	mutations: {
    
    
		addN(state, step) {
    
    
		// 变更状态
		state.count += step
		}
	}
})
// 触发mutation 
methods: {
    
     
	handle2() {
    
     
		// 在调用 commit 函数, 
		// 触发 mutations 时携带参数 
		this.$store.commit('addN', 3) 
	} 
}

this.$store.commit() is the first way to trigger mutations, which triggers mutations 第二种方式:

// 1. 从 vuex 中按需导入 mapMutations 函数
import {
    
     mapMutations } from 'vuex'

Through the imported mapMutations function, map the required mutations function to the methods method of the current component:

// 2. 将指定的 mutations 函数,映射为当前组件的 methods 函数
methods: {
    
    
	...mapMutations(['add', 'addN'])
}

3.4 Action

ActionUsed to handle asynchronous tasks.

If you change data through asynchronous operations, you must use Action instead of Mutation, but in Action, you still need to indirectly change data by triggering Mutation.

// 定义 Action
const store = new Vuex.Store({
    
     
	// ...省略其他代码 
	mutations: {
    
     
		add(state) {
    
     
			state.count++ 
		} 
	}, 
	actions: {
    
     
		addAsync(context) {
    
     
			setTimeout(() => {
    
     
				context.commit('add') 
			}, 1000) 
		} 
	} 
})
// 触发 Action
methods: {
    
    
	handle() {
    
    
		// 触发 actions 的第一种方式
		this.$store.dispatch('addAsync')
	}
}

Carry parameters when triggering the actions asynchronous task:

// 定义 Action 
const store = new Vuex.Store({
    
     
	// ...省略其他代码 
	mutations: {
    
     
		addN(state, step) {
    
     
			state.count += step 
		} 
	}, 
	actions: {
    
     
		addNAsync(context, step) {
    
     
			setTimeout(() => {
    
     
				context.commit('addN', step) 
			}, 1000)
        }
   }
})
// 触发 Action 
methods: {
    
    
	handle() {
    
     
		// 在调用 dispatch 函数, 
		// 触发 actions 时携带参数 
		this.$store.dispatch('addNAsync', 5) 
	} 
}

this.$store.dispatch() is the first way to trigger actions, which triggers actions 第二种方式:

// 1. 从 vuex 中按需导入 mapActions 函数 
import {
    
     mapActions } from 'vuex'

Through the imported mapActions function, map the required actions function to the methods method of the current component:

// 2. 将指定的 actions 函数,映射为当前组件的 methods 函数 
methods: {
    
     
	...mapActions(['addASync', 'addNASync']) 
}

3.5 Getter

GetterIt is used to process the data in the Store to form new data.

①Getter can process the existing data in the Store to form new data, similar to Vue's computed properties.

②When the data in the Store changes, the data in the Getter will also change.

// 定义 Getter
const store = new Vuex.Store({
    
    
	state: {
    
    
		count: 0
	},
	getters: {
    
    
		showNum: state => {
    
    
			return '当前最新的数量是【'+ state.count +'】'
		}
	}
})

The first way to use getters:

this.$store.getters.名称

Using getters 第二种方式:

import { mapGetters } from 'vuex'

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

Guess you like

Origin blog.csdn.net/Better_Xing/article/details/117532702