目录
1、项目代码
新建 demo05 文件夹 -》 在文件夹下创建 index.html 内容如下:
<!DOCTYPE html>
<html lang="zh_CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vuex 中的 state</title>
<!-- 1. 引入 vue 和 vuex -->
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.11/vue.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/vuex/3.1.3/vuex.js"></script>
</head>
<body>
<div id="app"></div>
<script>
// 2. 创建 store
const store = new Vuex.Store({
state: {
count: 2
}
})
// 创建一个 Counter 组件
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count() {
return store.state.count
}
}
}
const app = new Vue({
el: '#app',
// 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
store,
components: { Counter },
template: `
<div class="app">
<counter></counter>
</div>
`
})
</script>
</body>
</html>
注意:
每当 store.state.count
变化的时候, 都会重新求取计算属性,并且触发更新相关联的 DOM
2、子组件访问 store 中数据
3、mapState
辅助函数