13.vuex 状态管理

73 阅读1分钟

为什么用 vuex

Vuex

vuex-使用详解

State

  • state:存储状态(变量)

例一:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <script src="https://unpkg.com/vue"></script>
  <script src="https://unpkg.com/vuex"></script>
</head>
<body>

  <script>
    Vue.use(Vuex)
    
    const store = new Vuex.Store({
      state: {
        weather: '晴天'
      },
      mutations: {
        modifyWeather (state) {
          state.weather = '下雨'
          console.log(state.weather)
        }
      }
    })
    
    store.commit('modifyWeather')
    
    
  </script>
</body>
</html>

结果

"下雨"

例二:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <script src="https://unpkg.com/vue"></script>
  <script src="https://unpkg.com/vuex"></script>
</head>
<body>
  <div id="app"></div>
  
  <script>
    Vue.use(Vuex)
    
    const store = new Vuex.Store({
      state: {
        count: 0,
        firstName: 'hunger',
        lastName: 'valley'
      },
      mutations: {
        increment (state) {
          state.count++
        },
        
        modifyFirstName (state, newName) {
          state.firstName  = newName
        }
      },
      getters: {
        fullName(state) {
          return state.firstName + ' ' + state.lastName
        }
      }
    })
    
    const Counter = {
      template: `
       <div>
        <div>{{ count }}</div>
        <div>{{ firstName }} {{ lastName }}</div>
        <p>{{fullName}}</p>
        <button @click="add">+</button>
       </div>
        `,
      computed: {
        count () {
          return this.$store.state.count
        },
        //fullName () {
        //  return this.$store.getters.fullName
        //},
        ...Vuex.mapState(['firstName', 'lastName']),
        ...Vuex.mapGetters(['fullName'])
      },
      methods: {
        add () {
          this.$store.commit('increment')
        }
      }
    }
    
    const app = new Vue({
      el: '#app',
      store: store,
      components: { Counter },
      template: `
        <div class="app">
          <counter></counter>
        </div>
      `
    })

    
  </script>
</body>
</html>

image.png

Getter

  • getters:对数据获取之前的再次编译,可以理解为state的计算属性。我们在组件中使用 $sotre.getters.fun()

Mutation

  • mutations:修改状态,并且是同步的。在组件中使用$store.commit('',params)。这个和我们组件中的自定义事件类似。

Action

  • actions:异步操作。在组件中使用是$store.dispath('')

Module

  • modules:store的子模块,为了开发大型项目,方便状态管理而使用的。这里我们就不解释了,用起来和上面的一样。

vuex改造笔记本列表

初始化

//src\store\modules
//note.js
const state = {
}
const getters = {
}
const mutations = {
}
const actions = {
}

export default {
  state,
  getters,
  mutations,
  actions
}

把某个组件的核心数据搬到vuex下,对应的操作都用vuex的state,getters来做

云笔记-vuex note模块的完善与 NoteSidebar 的改造

云笔记-vuex改造NoteDetail

云笔记-vuex user模块