Several core concepts of Vuex state, getters, mutations, actions, modules
1. state single state tree/single data source
All shared state is placed in one store
2. Detailed use of vuex-getters
2.1, the basic use of getters
2.2, getters pass parameters as parameters
2.3. The above code example is as follows
src/store/index.js
import Vue from 'vue';
import Vuex from 'vuex'
//1、安装插件
Vue.use(Vuex)
// 2、创建对象
const store = new Vuex.Store({
state:{
counter:10,
students:[
{
id:100,name:'why',age:18},
{
id:101,name:'kobe',age:19},
{
id:102,name:'James',age:20},
{
id:103,name:'curry',age:21}
]
},
mutations: {
increment(state){
this.state.counter++
},
decrement(state){
this.state.counter--
}
},
getters:{
powerCounter(state){
return state.counter * state.counter
},
ageMore20(state){
return state.students.filter(s => s.age > 20)
},
ageMore20length(state,getters){
return getters.ageMore20.length
},
moreAgeStu(state){
// return function(age){
// return state.students.filter(s => s.age > 9)
// }
// 简便写法(箭头函数)
return age => {
return state.students.filter(s => s.age>age)
}
}
}
})
// 3、导出store对象
export default store
src/components/HelloBuex.vue
<template>
<div>
<!-- <h2>{
{
$store.state.counter}}</h2> -->
<h2>{
{
$store.getters.powerCounter}}</h2>
<!-- <h2>{
{
$store.getters.ageMore20}}</h2>
<h2>{
{
"年龄大于20的人数:"+$store.getters.ageMore20length}}</h2>
<h2>{
{
$store.getters.moreAgeStu(8)}}</h2> -->
</div>
</template>
<script>
export default {
name: "HelloVuex"
}
</script>
<style>
</style>
src/APP.vue
<template>
<div id="app">
<h2>{
{
message}}</h2>
<h2>{
{
$store.state.counter}}</h2>
<button @click="subtraction">-</button>
<button @click="addition">+</button>
<h2>{
{
$store.getters.powerCounter}}</h2>
<!-- <h2>{
{
$store.getters.ageMore20}}</h2> -->
<hello-vuex></hello-vuex>
</div>
</template>
<script>
import HelloVuex from './components/HelloVuex'
export default {
name: 'App',
components:{
HelloVuex
},
data(){
return{
message: '我是APP页面的组件'
}
},
methods:{
addition:function(){
this.$store.commit('increment')
},
subtraction:function(){
this.$store.commit('decrement')
}
}
}
</script>
<style>
</style>
3. Carrying parameters of vuex-mutations
3.1, carry a parameter
3.2. If you pass multiple data, put the data into an object
Before clicking:
After clicking:
3.3. Other submission styles of vuex-mutations
Printing effect:
3.4. The principle of responsiveness of data
As shown in the figure below, the info object is defined on the index.js page
Use these properties
on the APP.vue page Use these properties on the HelloVuex.vue page
Modify the value of the info attribute in index.js to
open the browser page, we found that the data of App.vue and HelloVuex.vue pages have changed accordingly. The reactive principle of vuex-data is used here.
3.5. Response rules for Mutations
Modify properties
4. Detailed explanation of the use of vuex-actions
5. Detailed explanation of the use of vuex-modules
src/store/index.js
src/App.vue