vuex的学习笔记(一)
vuex分为state,getters,mutation,actions,modules五大部分
1. vuex是个什么玩意?
vuex相当于一个数据库,里面存放着共享的数据。当A组件更改了某个数据,则在B访问的改数据就会发生相应的改变,vuex称之为“响应式”。
2. 怎么用这玩意?
先安装: npm install vuex --save
新建一个store.js文件
再引用:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
3. 具体是什么玩的?
在mai,js中导入 import store from "./store.js" (根据实际路径改)
new Vue({
el: '#app',
store,//拿来即用,在子组件中就可以使用了
render: h => h(App)
})
插入个小例子 store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
//状态,也就是数据
//使用state中的数据 this.$store.state.count
count: 1
},
mutations: {
//mutation必须是同步的函数,更改state中的count只能用mutations中的方法
//使用mutations中的方法 this.$store.commit('increament') 来触发事件
increament(state) {
state.count++
}
}
})