Vuex基本使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29729735/article/details/82804739

当页面有很多个组件之间需要进行复杂的数据传递时时,如果我们将公共数据放在一个公共地方统一管理,当一个组件改变了公共的数据时,其他组件页面就能感觉到(获取到改变后的数据),这是我们用到Vuex
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式,它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。简单可理解为一个集中管理数据的一个地方。
官方图:
在这里插入图片描述

右边虚线部分是公共存储区域。state存储所有的公共数据,当组件需要改变state里的数据时我们需要走一个流程:组件通过dispatch调用actions(这里存储一些异步方法或批量的同步方法)里的方法,然后actions通过commit调用Mutations(放一个一个的对state的修改)里的方法,只有通过mutations才能最终修改state的值。
有时可以组件直接通过commit来调用mutation里的方法。

使用:
安装
npm install --save vuex
创建一个src/store/index.js
state属性存储通用数据
getter属性类似于计算属性computed,对state里的数据进行再次计算,
actions:存放一系列方法,并通过ctx.commit()方法提交给mutations最终修改数据
mutaitions:存放一些列方法,最终修改数据

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

Vue.use(Vuex)
export default new Vuex.Store({
   state:{
		city:'北京',
	},
	
	actions:{
		change(ctx,city){//ctx上下文便于调用mutations,city数据
			console.log('action',city)
			ctx.commit('change',city)
		}
	},
	getter:{
    	doubleCity(state){
        	return state.city + ' ' + state.city
        }
    }
	mutations:{
		change(state,city){//state数据,city传过来的数据
			console.log('mutations',city)
			state.city = city
		}
	},
})

main.js引入

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import store from './store'

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,
  components: { App },
  template: '<App/>'
})

组件使用:
我们写在App.vue里,使用this.$store.state.属性,获取里边数据,然后使用this.$store.commit('方法名','数据')将数据传递到mutations执行改变数据或this.$store.dispatch('方法名','数据')将数据传递到actions调用mutations执行改变数据。

<template>
    <div>
       <div id="demo">
          {{city}}
          {{this.$store.state.doubleCity}}
        </div>
        <button @click="changeState">改变城市</button>
    </div>
</template>
<script>
export default{
    computed:{
       city(){
         return this.$store.state.city
       }
    },
    methods:{
        changeState(){
            //this.$store.commit('change','广东')
            this.$store.dispatch('change','广东')
        }
    },
}
</script>

高级使用(使用mapState,mapMutations映射函数):
App.vue

<template>
    <div>
       <div id="demo">
          {{this.city}}
        </div>
        <button @click="changeState">改变城市</button>
    </div>
</template>
<script>
import { mapState ,mapMutations} from 'vuex'
import { mapState ,mapMutations} from 'vuex'
export default{
    computed:{
       ...mapState(['city'])//将
    },
    methods:{
        changeState(){
            this.change('广东')//直接调用change方法
        },
        ...mapMutations(['change'])//将将change方法映射到mutations的change方法
    },
}
</script>

总结
上述简单描述了一下vuex存储或改变数据的流程
vuex的基本用法如上,更多用法参见文档

猜你喜欢

转载自blog.csdn.net/qq_29729735/article/details/82804739