vuex 使用注意事项

一、 安装

npm install vuex --save

二、 使用

在main.js中

import vuex from 'vuex'
Vue.use(vuex);
var store = new vuex.Store({//store对象

	//state:保存的是原始数据,可以理解为需要共享的数据或状态,
	 state:{
	     show:false,
	     num: 2
	 },
	 
	//getters:可以理解为是staore的计算属性,可以实现就store的计算,但是不能更改。例如你想知道两个值相加、相乘。都是非常不错的选择。
	 getters: {
		getValue (state) {
		    return state.num*2;
		  }
	 },

	//mutations:mutations中的方法可以对state中的数据进行改变。
	mutations: {
		changeActiveName (state, activeNav) {
			state.activeName = activeNav
		},
		changeNum (state, number) {
			state.num= number
		}
	},

	//action:action中的方法可以调用mutations中的方法,但不可修改state中的原始数据。
	//action中的函数可以使用ajax的技术对服务器进行数据交互。并且可以在回调中使用commit调用mutations中的方法,
	//例如通过context.commit('increment', price)increment是需要调用mutations中的方法名,price是需要传入的参数。 
	//mutations中的方法再去更改state的原始数据。
	actions: {
		increase (context, price) {
			context.commit('changeNum ', price)
		}
	}
})

new Vue({
  el: '#app',
  router,
  store,// 加入这个,使用store
})

三、 调用

this.$store.state.path

如何在组件中使用getters内的方法?

computed: {
  getTotal () {
    return this.$store.getters.getValue 
  }
}

如何在组件中使用mutations内的方法?

methods: {
     changeNav() {
       this.$store.commit('changeActiveName ', 'abc')
     },
     changeNum(){
		 this.$store.commit('changeNum ', 5)
	}
}

如何在组件中使用actions内的方法?

  methods: {
     addOne () {
       this.$store.dispatch('increase', 9)
     }
   }

https://blog.csdn.net/qq_38188485/article/details/80674462

发布了38 篇原创文章 · 获赞 5 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_39423672/article/details/81236634
今日推荐