版本 ext s函数 快照 view turn highlight stat
Vuex 是一个专为 vue.js 应用程序开发的状态管理模式
单个父子组件的数据绑定可能会简单一点,多个组件之间的数据绑定就比较麻烦了,vuex就是解决这个的
Vuex 也集成到 Vue 的官方调试工具 devtools extension
提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。
状态管理模式:
1.store数据源--》对应vue data
2.view模板--》对应 vue temolate
3.actions响应--》对应vue methods函数
开发大型单页应用比较适合用(非简单单页应用)
一、先新建一个store对象
1.先来一些数据和一个简单的修改数据函数
- // 如果在模块化构建系统中,请确保在开头调用了 Vue.use(Vuex)
- const store = new Vuex.Store({
- state: {
- count: 0
- },
- mutations: {
- increment(state) {
- state.count++
- }
- }
- })
2.store对象有两个方法
- store.commit(‘increment‘) //执行函数
- console.log(store.state.count) // -> 1 //state查询\获取
二、将数据源从根组件注入到需要的每一个子组件中(需调用
):
- Vue.use(Vuex)
1.新建根目录下vue实例,并建立store对象
- const app = new Vue({
- el: ‘#app‘,
- // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
- store,
- components: {
- Counter
- },
- //计数器组件
- template: ` < div class = "app" > <counter > </counter>
- </div > `
- })
2.子组件能通过
访问父组件store对象
- this.$store
- const Counter = {
- template: `<div>{{ count }}</div>`,
- computed: {
- count () {
- return this.$store.state.count
- }
- }
- }
三、辅助函数mapState
子组件获取到数据后,想返回一个计算出来的值,可以用这个vuex自带的辅助函数
1.假设子组件data里面有一个localCount数据,可以这样用
- // 在单独构建的版本中辅助函数为 Vuex.mapState
- import { mapState } from ‘vuex‘
- export default {
- // ...
- computed:
- mapState({
- // 箭头函数可使代码更简练
- count: state => state.count,
- // 传字符串参数 ‘count‘ 等同于 `state => state.count`
- countAlias: ‘count‘,
- // 为了能够使用 `this` 获取局部状态,必须使用常规函数
- countPlusLocalState (state) {
- return state.count + this.localCount
- }
- })
- } //这样就返回了根组件数据count加上子组件数据localCount
2.当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给
传一个字符串数组。
- mapState
- computed: mapState([
- // 映射 this.count 为 store.state.count
- ‘count‘
- ])
学习自:https://vuex.vuejs.org/zh-cn/installation.html
vuex学习--(1)
来源: http://www.bubuko.com/infodetail-2295852.html