安装Vuex
安装Vuex命令
1、
npm install vuex –save
2、
在src目录下创建store
在store目录下创建index.js
3、
index.js中写入
类似于router
4、
在main.js中引入store
index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state:{
},
getters:{
},
mutations:{
},
actions:{
},
})
export default store
main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
new Vue({
store,
router,
render: function (h) { return h(App) }
}).$mount('#app')
Vuex属性
1.state
vuex的基本数据,用来存变量,页面中用this.$store.state.变量名字来接收
2.getters
用来state的计算,组件中使用 this.$store.getters.函数名
在属性中使用函数的方法
函数名(){
return state.变量名 + or - or * or
}
3.mutations
用来更新state中的变量,第一个参数是state,第二个参数是要将变量更新为的值,提交更新state的方法必须是同步!
组件中使用this.$store.commit(函数名,‘参数’)
属性中使用
函数名(state,参数){
state.变量名 += or = 参数
}
4.actions
跟mutations属性作用是一样的,同之处是actions是异步
组件中使用,this.$store.dispatch(‘actions中的函数名’,‘参数’)
属性中使用
函数名(context,参数){
context.commit(‘mutations中的函数名’,‘参数’)
}