vuex的基础使用

安装vuex

npm install vuex --save
//或者
yarn add vuex (推荐使用)

main.js

import Vue from 'vue'
import store from './store'
new Vue({
  store,
}).$mount('#app')

src/store/index.js (无该文件则自己新建)

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
	  msg:"小歪"
  },
  mutations: {},
  actions: {},
  modules: {}
})

组件使用:
.html

<h1>{{this.$store.state.msg}}</h1>

.js

console.log(this.$store.state.msg)
store使用辅助函数:

.js

<script>
import {mapState} from 'vuex'
export default {
	data() {
		return {}
	},
	methods: {},
	computed: {
		// 使用state辅助函数,使用对象方式时,名称可以不一致
		...mapState({
			msg:state=>state.msg
		})
	},
}
</script>

.html

<h1>{{msg}}</h1>

mutations使用介绍(全局方法)

export default new Vuex.Store({
  state: {
	  count:0
  },
  mutations: {
	 add(state){
		state.count = state.count+1
	}
  },
  actions: {},
  modules: {}
})

组件调用mutations方法:

methods:{
	countadd(){
		this.$store.commit('add')
	}
}
mutations使用辅助函数:
import {mapMutations} from 'vuex'
export default new Vuex.Store({
  state: {
	  count:0
  },
  mutations: {
	 add(state){
		state.count = state.count+1
	}
  },
  actions: {},
  modules: {}
})

组件调用mutations方法:

methods:{
	// 使用mutations辅助函数,使用对象方式时,名称可以不一致
	...mapMutations({
	 	muCountAdd:'add'
	}),
	//调用 this.muCountAdd()
}