Vuex的核心就是store(仓库)。里面包含着项目中共用的数据状态。
我们可以来看一个简单的例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>vuex</title>
</head>
<body>
<h3>vuex开始---state</h3>
<div id="app"></div>
</body>
</html>
<script type="text/javascript" src="https://cdn.bootcss.com/vue/2.6.10/vue.js"></script>
<script type="text/javascript" src="https://cdn.bootcss.com/vuex/2.2.0/vuex.js"></script>
<script type="text/javascript">
// 创建一个store
const store = new Vuex.Store({
state: {
count: 0
},
// 相当于vue中的method,里面定义的是一个函数方法
mutations: {
increment (state) {
state.count++
}
}
})
// 创建一个组件
const Counter = {
template: `<div @click="changeState">{{ count }}</div>`,
computed: {
count () {
return this.$store.state.count
}
},
methods: {
// 触发事件后提交increment事件,从而改变仓库中的值
changeState () {
this.$store.commit('increment')
console.log(this.$store.state.count)
}
}
}
let vm = new Vue({
el: '#app',
// 将 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件中
store,
data () {
return {
count: 1,
localCount: 2
}
},
// 注册组件,一定要在template使用
components: {
Counter
},
template: `<Counter></Counter>`,
})
</script>
可以看出Vuex的状态存储是响应式的。而改变store中状态的唯一途径就是显式地提交(commit) mutation。