bilibili学习之vuex 中的mutations

 Vuex的官网链接https://vuex.vuejs.org/zh/

vuex也是插件,需要安装

npm install vuex --save

// 1.提取出一个公共的store对象,用于保存在多个组件中共享的状态
//2.将store对象放置在new Vue对象中,这样可以保证在所有的组件中都可以使用到
//3.在其他组件中使用store对象中保存的状态即可
//通过this.$store.state.属性的方式来访问状态
//通过this.$store.commit('mutation中方法')来修改状态 

创建store目录,下面建一个index.js。

  • 安装插件
  • 创建对象
  • 导出

state、mutations、actions 、getters 、modules都是方法

bilibili学习之vuex 中的mutations_第1张图片

然后在main.js中导入:

bilibili学习之vuex 中的mutations_第2张图片

在APP.vue中写:






 在components目录下建HelloVuex.js






在index.js中:

import Vue from 'vue'
import Vuex from 'vuex'
//1安装插件
Vue.use(Vuex)

//2创建对象
const store = new Vuex.Store({
	state:{
		counter:100
	},
	mutations:{
		increment(state){
			state.counter++
		},
		decrement(state){
			state.counter--
		}
	},
	actions:{
		
	},
	getters:{
		
	},
	modules:{
		
	}
})
export default store

效果图

bilibili学习之vuex 中的mutations_第3张图片

 bilibili学习之vuex 中的mutations_第4张图片

 如果要修改state中的内容,要通过mutations进行修改,安装插件Devtools可对修改的内容进行监听,当有异步操作时要使用actions。具体可到官方网站查看。

我还没学会那。

 

你可能感兴趣的:(Vue)