vuex--学习笔记

1.概念(略):官方文档

2.安装

npm install vuex --save

3.项目目录结构

4.在main.js引入 创建的store仓库

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './vuex/store'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

 

5.templates:

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <div>{{ count }}</div>
    <button @click="add">button</button>
  </div>
</template>

<script>
import * as GetterTypes from '@/constants/GetterTypes'
import * as MutationTypes from '@/constants/MutationTypes'
import { mapGetters, mapMutations } from 'vuex'
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  computed: {
    ...mapGetters([
      [GetterTypes.GET_COUNT]
    ]),
    ...mapGetters({
      count: [GetterTypes.GET_COUNT]
    })
  },
  methods: {
    ...mapMutations([
      [MutationTypes.SET_COUNT]
    ]),
    ...mapMutations({
      [MutationTypes.SET_COUNT]: MutationTypes.SET_COUNT
    }),
    add () {
      let count = this.count + 1
      this[MutationTypes.SET_COUNT](count)
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

vuex文件夹

store.js

import Vue from 'vue'
import Vuex from 'vuex'
import * as mutations from './mutations'
import * as getters from './getters'

Vue.use(Vuex)

const state = {
  // 计数改变
  count: 0
}

export default new Vuex.Store({
  state,
  getters: getters.getters,
  mutations: mutations.mutations
})

mutations.js:

import * as MutationTypes from '@/constants/MutationTypes'

export const mutations = {
  [MutationTypes.SET_COUNT]: (state, count) => {
    state.count = count
  }
}

getters.js:

/**
 * 状态的派生属性
 */
import * as GetterTypes from '@/constants/GetterTypes'

export const getters = {
  [GetterTypes.GET_COUNT]: (state) => {
    return state.count
  }
}

constants

GetterTypes.js:

// 获取
export const GET_COUNT = 'getCount'

MutationTypes.js:

// 设置
export const SET_COUNT = 'setCount'

 

posted @ 2019-04-22 19:24  riven.lcs  阅读(189)  评论(0编辑  收藏  举报