VueX扒文档的整理

288 阅读1分钟

VueX的初步接触使用

vuex官方介绍: vuex.vuejs.org/zh/

state 单一状态树

<!--store.js-->
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
  	count: 0
  }
})
<!--页面中使用-->
<template>
  <div>state页面
  	<p>直接使用:{{this.$store.state.count}}</p>
  	<p>辅助函数使用:{{count}}</p>
  </div>
</template>
<script>
// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'
export default {
	// 映射 this.count 为 store.state.count
	// computed: mapState(['count']),
	computed: {
	  // 使用对象展开运算符将此对象混入到外部对象中
	  // ...mapState(['count'])
	  ...mapState({
	    count: 'count'
	  })
	}
}
</script>

Getter

有时候我们需要从 store 中的 state 中派生出一些状态(可以认为是 store 的计算属性)

<!--store.js-->
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
  	todos: [
      { id: 1, text: '文字1', done: true },
      { id: 2, text: '文字2', done: false }
    ]
  },
  getters: {
  	// Getter 接受 state 作为其第一个参数
    doneTodos: state => {
    	return state.todos.filter(todo => todo.done)
    },
    // 接受其他 getter 作为第二个参数:
    doneTodosCount: (state, getters) => {
		return getters.doneTodos.length
	},
	// 通过让 getter 返回一个函数,来实现给 getter 传参。
	getTodoById: (state) => (id) => {
		return state.todos.find(todo => todo.id === id)
	}
  }
})
<!--页面中使用-->
<template>
  <div>getter页面
  	<div @click="conGetter">打印getter</div>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
	created(){
		// Getter 会暴露为 store.getters 对象
		console.log(this.$store.getters.doneTodos) // [{"id":1,"text":"文字1","done":true}]
		console.log(this.$store.getters.doneTodosCount) // 1
		console.log(this.$store.getters.getTodoById(2)) // { id: 2, text: '文字2', done: false }
	},
	computed: {
		// 使用对象展开运算符将 getter 混入 computed 对象中
		...mapGetters([
		  'doneTodosCount',
		  'getTodoById'
		]),
		...mapGetters({
			// 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
			doneCount: 'doneTodosCount'
		})
	},
    methods: {
        conGetter(){
        	console.log(this.doneTodosCount) //1
        	console.log(this.getTodoById(2)) //{ id: 2, text: '文字2', done: false }
        	console.log(this.doneCount) //1
        }
    }
}
</script>

Mutation

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。通过调用 store.commit 方法来提交 mutation。

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

export default new Vuex.Store({
  state: {
  	count: 0,
  },
  getters: {},
  mutations: {
  	addCount(state){
  		state.count++;
  	},
  	// 向 store.commit 传入额外的参数,即 mutation 的 载荷(payload)
  	naddCount(state,n){
  		state.count += n;
  	},
  	// 大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读
  	paddCount(state, payload) {
		state.count += payload.amount
	},
  },
  actions: {}
})
<template>
  <div>mutation页面
	<div @click="$store.commit('addCount')">点击count+1:{{count}}</div>
	<div @click="$store.commit('naddCount',10)">点击count+n:{{count}}</div>
	<div @click="$store.commit('paddCount',{amount: 20})">点击count+amount:{{count}}</div>
	<div @click="$store.commit({type: 'paddCount',amount: 30})">对象风格提交:{{count}}</div>
	<div @click="addCount">辅助函数:{{count}}</div>
	<div @click="add1">辅助函数:{{count}}</div>
	<div @click="naddCount(11)">辅助函数携带荷载:{{count}}</div>
  </div>
</template>
<script>
import { mapState,mapMutations } from 'vuex'
export default {
    computed: {
        ...mapState(['count'])
    },
    methods: {
    	// 使用 mapMutations 辅助函数,`mapMutations` 也支持载荷
    	...mapMutations([
    	    // 将 `this.addCount()` 映射为`this.$store.commit('addCount')`
    	    'addCount', 
    	    'naddCount'
    	]),
        ...mapMutations({
                // 将 `this.add()` 映射为 `this.$store.commit('increment')`
        	add1: 'addCount' 
        })
    }
}
</script>

Actions简单使用

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
  	count: 0
  },
  getters: {},
  mutations: {
  	addCount(state){
  		state.count++;
  	},
  	// 向 store.commit 传入额外的参数,即 mutation 的 载荷(payload)
  	naddCount(state,n){
  		state.count += n;
  	},
  	// 大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读
  	paddCount(state, payload) {
		state.count += payload.amount
	},
  },
  actions: {
    increment (context) {
        context.commit('addCount')
    },
    increment1 ({ commit }, n) {
        commit('naddCount', n)
    },
    // actions异步操作
    addAsync ({ commit }) {
        setTimeout(() => {
            commit('addCount')
        }, 1000)
    }
  }
})
<template>
  <div>action页面
	<div @click="$store.dispatch('increment')">action修改count:{{count}}</div>
	<div @click="$store.dispatch('increment1',10)">action修改count:{{count}}</div>
	<div @click="$store.dispatch('addAsync')">action异步修改count:{{count}}</div>
	<div @click="increment">辅助函数actions修改count:{{count}}</div>
	<div @click="add1(11)">辅助函数actions修改count:{{count}}</div>
  </div>
</template>
<script>
import { mapState,mapActions } from 'vuex'
export default {
	computed: {
		...mapState(['count'])
	},
    methods: {
        ...mapActions([
            // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
            'increment'
        ]),
        ...mapActions({
            // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
            add1: 'increment1' 
        })
    }
}
</script>