您的当前位置:首页正文

vuex学习笔记

来源:华佗小知识
一、一个简单的学习案例
<body>
  <div id="app">
    <p>{{ count }}</p>
    <p>
      <button @click="increment">+</button>
      <button @click="decrement">-</button>
    </p>
  </div>
</body>
<script type="text/javascript">
  const store = new Vuex.Store({
    state: {
      count: 0
    },
    mutations: {
      increment: state => state.count++,
      decrement: state => state.count--
    }
  })
  new Vue({
    el: '#app',
    computed: {
      count() {
      // 每当store.state.count发生变化的时候,都会重新求取计算属性,并且触发更新相关联的DOM
        return store.state.count
      }
    },
    methods: {
      increment() {
        
      },
      decrement() {
        
      }
    }
  })
</script>
屏幕快照 2018-07-24 上午11.45.52.png
二、vuex工作原理
vuex工作原理
state
// 访问方法一:
const Counter = {
  template: `<div>{{ count }}</div>`,
  computed: {
    count () {
      return this.$store.state.count
    }
  }
}
// 访问方法二:
// 在单独构建的版本中辅助函数为 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
    }
  })
}
Getter方法

      有时候我们需要从store中的state中派生出一些状态,例如对列表进行过滤并计数,getter可以被认为是store的计算属性,如同计算属性一样,getter的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生改变才会被重新计算;

// 定义方法
getters: {
  // ...
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}
// 访问方法一
computed: {
  doneTodosCount () {
    return this.$store.getters.doneTodosCount
  }
}
// 访问方法二
import { mapGetters } from 'vuex'

export default {
  // ...
  computed: {
  // 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
  }
}
提交mutation,mutation中都是同步事务
// commit方法
computed: {
    ...mapState({
      gymList: 'gymList',
    }),
    ...mapGetters({
      gym: 'currentGym',
    }),
    gymId: {
      get() {
        return this.$store.state.gymId
      },
      set(value) {
         value)
         this.gym.roomList ? this.gym.roomList[0].id : '')
      }
    },
// 辅助函数
import { mapMutations } from 'vuex'

export default {
  // ...
  methods: {
    ...mapMutations([
      'increment', // 将 `this.increment()` 映射为 
      // `mapMutations` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为  amount)`
    ]),
    ...mapMutations({
      add: 'increment' // 将 `this.add()` 映射为 
    })
  }
}
Action

      1)Action类似于mutation,不同在于:Action提交的是mutation,而不是直接变更状态;
      2)Action可以包含任意异步操作;

// 使用mapActions辅助函数提交
import { mapActions } from 'vuex'

export default {
  // ...
  methods: {
    ...mapActions([
      'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`

      // `mapActions` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
    ]),
    ...mapActions({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
    })
  }
}
if (!state.gymId) {
     gymList[0].gym.id)
}
一个完整的store包含
const store = new Vuex.Store({
    state: {
      gymList: [],
      gymId: null,
      roomId: null,
      user: {
        username: null,   // 登录用户名
        role: null        // 角色
      }
    },
    //plugins: process.env.NODE_ENV !== 'production' ? [createLogger()] : [],
    getters: {
      currentGym: state => {
        return _.find(state.gymList, {gym: {id: state.gymId}})
      },
    },
    mutations: {
      setGymList(state, payload) {
        state.gymList = payload;
      },
      setGymId(state, payload) {
        state.gymId = payload;
      },
      setRoomId(state, payload) {
        state.roomId = payload;
      },
      setUser(state, payload) {
        state.user = payload
      }
    },
    actions: {
      fetchGymList(context) {
        axios.get(`${api_host}/lego/manage/gym/list`).then((res) => {
          let gymList = res.data.data;
          let state = context.state;

          if (!state.gymId) {
             gymList[0].gym.id)
          }
          if (!state.roomId) {
             gymList[0].roomList[0]);
             gymList[0].roomList[0].id);
          }

           gymList)
        });
      }
    },
    modules: {}
});