zoukankan      html  css  js  c++  java
  • Vue创建四:使用vuex

    1、在vue项目的src目录下创建store文件夹,创建index.js文件

    //store/index.js
    import Vue from 'vue'
    import Vuex from 'vuex'
    
    Vue.use(Vuex);
    
    const store = new Vuex.Store({
    	state: {
    		count: 1,
    		beforeCount:0
    	},
    	mutations: {
    		increment (state) {
    			state.beforeCount = state.count++
    		}
    	}
    });
    export default store
    

    2、store

    main.js中注册 store 选项,该 store 实例会注入到根组件下的所有子组件中,且子组件能通过 this.$store 访问到

    import store from './store'
    ...
    new Vue({
      el: '#app',
      router,
      store,
      components: { App },
      template: '<App/>'
    })
    

    3、state

    在子组件中访问更改状态,有多种方式

      1) this.$store.state.count

      2) 当需要获取多个状态时,使用mapState 辅助函数,它会返回一个对象

    <template>
    	<div>
    		检查报告详情
    		<p>{{count}}</p>
    		<p>{{beforeCount}}</p>
    		<button type="button" @click="handleCountAdd">click</button>
    	</div>
    </template>
    
    <script type="text/javascript">
    	import { mapState } from 'vuex'
    	export default {
    		name: 'ReportDetail',
    		computed: /*1、mapState 函数返回的是一个对象,获取多个状态
    		mapState({
    			count: state=>state.count,
    			beforeCount: 'beforeCount'
    		})*/
    		/*2、当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。
    		mapState(['count','beforeCount'])*/
    		/*3、与局部计算属性混合使用,将多个对象合并为一个,以使我们可以将最终对象传给 computed 属性***/
    		{	 
    			localComputed () { /* ... */ },
    			...mapState(['count','beforeCount'])
    		},
    		methods: {
    			handleCountAdd () {
    				this.$store.commit('increment');
    			}
    		}
    	}
    </script>
    
    <style lang="scss" scoped>
    	
    </style>
    

    当需要对state中的数据做某种计算时,一般使用

    computed: {
      listCount () {
         this.$store.state.list.filter(item=>item>3).length
      }          
    }  

    当多个子组件需要相同的计算时,可以将这些方法写到store的getters中

    state: {
    		count: 1,
    		beforeCount:0,
    		list:[1,2,3,4,5,6,7],
    		todos: [{id: 1,name: 'admin'},{id: 2,name: 'superadmin'}]
    	},
    	getters: {//多个组件需要用到此属性时,使用getters.
    		//可以认为是 store 的计算属性:
    		//getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
    		//Getter 会暴露为 store.getters 对象,你可以以属性的形式访问这些值:store.getters.listCount
    		listCount:state => state.list.filter(item=>item>3).length,
    		//让 getter 返回一个函数,来实现给 getter 传参。
    		//getter 在通过方法访问时,每次都会去进行调用,而不会缓存结果
    		getTodoById: (state) => (id) => {			
    		    return state.todos.find(todo => todo.id === id)
    		  }
    	},  

    子组件调用

                  /*listCount () {
    				return this.$store.getters.listCount//.state.list.filter(item=>item>3).length
    			},*/
    			todoItem () {
    				return this.$store.getters.getTodoById(this.count);
    			},
    			//mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性:
    			...mapGetters(['listCount'])
    

    4、mutation

    更改 Vuex 的 store 中的状态的唯一方法是提交 mutation

    每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数

    触发mutation中的事件:store.commit('increment')

    向 store.commit 传入额外的参数,即 mutation 的 载荷(payload)

    //.vue
    methods: {
    			handleCountAdd () {
    				this.$store.commit('increment',3);
    			}
    		}
    
    //store
    mutations: {
    		increment (state,num) {
    			if(num){
    				state.beforeCount = state.count = num
    			}else{
    				state.beforeCount = state.count++	
    			}
    			
    		}
    	}
    

    载荷一般是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读

    methods: {
    			handleCountAdd () {
    				this.$store.commit('increment',{num:3});
    			}
    		}
    //
    mutations: {
    		increment (state,payLoad) {
    			if(payLoad){
    				state.beforeCount = state.count = payLoad.num
    			}else{
    				state.beforeCount = state.count++	
    			}
    			
    		}
    	}  
    methods: {//mapMutations提交mutation:使用方式同mapState
    			/*handleCountAdd () {
    				//this.$store.commit('increment',{num:3});
    				this.$store.commit({type:'INCREMENT',num:3})
    			}*/
    			...mapMutations({
    				handleCountAdd: 'INCREMENT'
    			})
    		}
    

      

    对象的方式提交:type=对应的mutation方法

    this.$store.commit({type:'increment',num:3})

    mutation 必须是同步函数  

    在 mutation 中混合异步调用会导致你的程序很难调试。例如,当你调用了两个包含异步回调的 mutation 来改变状态,你怎么知道什么时候回调和哪个先回调呢?这就是为什么我们要区分这两个概念。为了处理异步操作,让我们来看一看 Action

    5、Action

    Action 类似于 mutation,不同在于:

    • Action 提交的是 mutation,而不是直接变更状态。
    • Action 可以包含任意异步操作。
    actions: {
    	   /* INCREMENT (context) {
    	      context.commit('INCREMENT')
    	    }*/
    	    INCREMENT ({ commit }) {//参数结构
    		    commit('INCREMENT')
    		  }
    	  }
    

      Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。

    Action 通过 store.dispatch 方法触发,在 action 内部执行异步操作

    methods: {
    	handleCountAdd () {
    	  //this.$store.commit('increment',{num:3});
          //this.$store.commit({type:'INCREMENT',num:3})
      	  this.$store.dispatch('INCREMENTASYNC')
    	}
    }
    
    //
    import types from './mutationtypes'
    actions: {
    	   /* INCREMENT (context) {
    	      context.commit('INCREMENT')
    	    }*/
    	    [types.INCREMENT] ({ commit }) {//参数结构
    		    commit('INCREMENT')
    		},
    		[types.INCREMENTASYNC] ({ commit }) {
    			setTimeout(()=>{
    				commit('INCREMENT')	
    			},500)			
    		}
    	  }
    

    Actions 支持同样的载荷方式和对象方式进行分发

    在组件中分发 Action

    使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用

    import { mapActions } from 'vuex'
    methods: {
    			/*handleCountAdd () {
    				//this.$store.commit('increment',{num:3});
    				//this.$store.commit({type:'INCREMENT',num:3})
    				this.$store.dispatch('INCREMENTASYNC')
    			}*/
    			/*...mapMutations({
    				handleCountAdd: 'INCREMENT'
    			})*/
    			...mapActions({
    				handleCountAdd:'INCREMENTASYNC'
    			})
    		}
    

      

    store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise

    handleCountAdd () {				
    	this.$store.dispatch('INCREMENTASYNC').then(()=>{
    		console.log('async end')
    	})
    }
    

    6、 modules

    将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割

    //store.js
    const moduleA = {
    	state: {
    		name: "Alice"
    	}
    }
    const moduleB = {
    	state: {
    		name: "Bush"
    	}
    }
    const store = new Vuex.Store({
    	modules: {
    		a: moduleA,
    		b: moduleB
    	}
    })
    
    //c.vue
    computed: {
    		moduleName () {
    			return this.$store.state.a.name
    		}
    	}
    

      

  • 相关阅读:
    堆和栈的区别!
    产品经理和程序员的爱恨情仇
    字符串MD5加密运算
    事件驱动模型。。。。有时间弄
    Apache服务器httpd.exe进程占用cpu超过50%的解决方法
    ZigBee Xbee S2通讯设置
    pipe-filter 真难找啊
    javacomm64位用不了,可以使用RXTXcomm for x64
    导入 sun.net.TelnetInputStream; 报错
    linux下gedit读取txt乱码解决办法
  • 原文地址:https://www.cnblogs.com/Youngly/p/9226133.html
Copyright © 2011-2022 走看看