每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。Vuex 和单纯的全局对象有以下两点不同:
Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。
vue.js之vue-cli中使用vuex
1.先安装vuex
npm install vuex --save
2.再在store中新建index.js
import Vue from 'vue'
import Vuex from 'Vuex'
Vue.use(Vuex)
let store = new Vuex.Store({
state: {
loginState:''
},
getter:{
state(){
let state = '';
return state
}
},
mutations: {
}
})
export default store
3.最后在src/main.js中加入
import Vue from 'vue'
import App from './App'
import router from './router'
//此处为新增的
import store from './store'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
//此处为新增的
store,
components: {
App
},
template: '<App/>'
})
使用vuex
//获取state里面的数据
computed: {
//登录
loginState() {
return this.$store.state.loginState
},
},
//获取getters里面的数据
computed: {
//登录
state() {
return this.$store.getters.state
},
},
//执行mutations的方法
this.$store.commit("方法名",data);
网友评论