安装
npm install vuex --save
引用
//store.js
import vuex from 'vuex'
Vue.use(vuex);
var store = new vuex.Store({//store对象
state:{
show:false
}
})
//main.js
import vue from 'vue'
import store from './store.js'
new Vue({
el: '#app',
router,
store,//使用store
template: '<App/>',
components: { App }
})
state:存放转态
//定义
const store = new Vuex.Store({
state: {
count: 0
}
})
//使用
console.log(this.$store.state.count)
getter :计算属性
//定义 store.js
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
//通过属性访问(不传参)
doneTodos: state => {
return state.todos.filter(todo => todo.done)
},
//传参
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
}
}
})
//简单的使用index.vue
<scripte>
computed: {
doneTodosCount () {
return this.$store.getters.doneTodosCount
}
}
</script>
//注意,getter 在通过方法访问时,每次都会去进行调用,而不会缓存结果。
mutation:事件类型 (type) 和回调函数(同步函数)
//定义
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
})
//使用
store.commit('increment')
//提交载荷(Payload)
mutations: {
increment (state, n) {
state.count += n
}
}
//使用
store.commit('increment', 10)
//在组件中提交 Mutation
import { mapMutations } from 'vuex'
export default {
// ...
methods: {
...mapMutations([
'increment',
// 将 `this.increment()` 映射为 `this.$store.commit('increment')`
// `mapMutations` 也支持载荷:
'incrementBy'
// 将 `this.incrementBy(amount)` 映射为`this.$store.commit('incrementBy', amount)`
]),
...mapMutations({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
})
}
}
action:异步操作
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
store.dispatch('increment')
//store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise:
actions: {
actionA ({ commit }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('someMutation')
resolve()
}, 1000)
})
}
}
//等价于
store.dispatch('actionA').then(() => {
// ...
})
module:模块化
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态