vuex状态管理初学demo,一看就会

vuex状态管理初学,一看就会

1. vuex安装:

			npm install vuex --save

2. 新建store.js
新建store.js
store.js中代码如下

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
    
    
  //state理解为管理状态的容器,变量在这里面声明,像vue页面的data()
  state: {
    
    
    count:0
  },methods
  //mutation理解为控制状态的方法,像vue页面的methods
  mutations: {
    
    
    increment (state) {
    
    
      state.count++
    }
  }
})
//最后export一下,才能在main.js中引用。
export default store

3. 在main.js中引用

	import store from './store'

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

4.在vue页面中调用vuex中管理的数据

<template>
	<div>
		<div id="main">
			<el-button @click="show()">show</el-button>
			<el-button @click="change()">change</el-button>
		</div>
		<div>{
    
    {
    
    count}}</div>
	</div>
</template>

<script>
	import {
    
    mapState} from 'vuex'
	export default{
    
    
		data(){
    
    
			return{
    
    }
		},
		//获取count
		computed:{
    
    
			...mapState({
    
    
				count:state=>state.count
			})
		},
		methods:{
    
    
		    //在控制台打印
			show(){
    
    
				console.log(this.count)
			},
			//调用一下increment,看看能否改编count的值
			change(){
    
    
				this.$store.commit('increment')
			},
		}
	}
</script>

结束语:鄙人才疏学浅,不对之处多多海涵,多多赐教。若有不明之处,欢迎留言。

猜你喜欢

转载自blog.csdn.net/Dawnchen1/article/details/109319662