vue 系列 -- vuex 的学习记录1

530 阅读2分钟

vuex 是什么

官方文档:

image.png

形象比喻:

vuex 就相当于一个放置物品的仓库(对象),所有人(组件)都可以把东西(属性及其值)放到仓库里面(存数据)和拿走仓库里的东西(取数据)

vuex 要解决什么问题

官方文档:

image.png

通俗理解:

这些物品是大家共用的,如果没有这个仓库,大家拿来拿去很不方便,所以建了个公共的仓库去放这些物品,大家都统一到这里存取

image.png

也就是说,开发大型单页应用的时候使用 vuex 能够更好地解决问题

比如:做商城项目时,用户在商品详情页点击加入购物车按钮,则应用需要把该商品的数据整块打包给 state 里面,然后购物车列表页再从 state 里面拿去该商品的数据然后显示出来

用 vue 去类比 vuex

我们用 vue 去类比 vuex 会更加的好理解一点,这里借用 通俗理解vuex原理---通过vue例子类比 这篇文章来解读

先来看一个简单的 vue 响应式的例子

vue 中的 data 、methods、computed 三者可以实现响应式

  1. 视图通过点击事件,触发 methods 中的 increment 方法
  2. 该方法更改 data 中 count 的值
  3. 一旦 count 值发生变化,computed 中的函数能够把 getCount 更新到视图
    <template>
      <div id="app">
        <button @click="increment"></button>
        {{getCount}}
      </div>
    </template>
    
    <script>
    new Vue({
        el: "#app",
        // state
        data () {
         return {
            count: 0
         }
        },
        
        // actions
        methods: {
         increment () {
            this.count++
         }
        },
        
         // view
        computed: {
          getCount(){
            return this.count
          }
        },
    })
    </script>

用 vuex 来实现同样的功能

二者类比如下:

image.png

假设没有 actions,他们的对应关系是这样的:

  • 更改数据 mutations → methods
  • 获取数据 getters → computed
  • 数据 state → data

然后用 vuex 来实现以上的功能:

  1. 视图通过点击事件,触发 mutations 中的 increment 方法
  2. 该方法更改 state 中 count 的值
  3. 一旦 count 值发生变化,getters 中的函数能够把 getCount 更新到视图

我们看官网的图片:

image.png

另外的 action、dispatch、commit 是干嘛的?

  • action 可以理解是为了处理异步而多加的一层
  • 组件通过 dispatch 可以触发 actions 中的方法
  • actions 中的 commit 可以触发 mulations 中的方法

用 vuex 实现的代码:

store.js

        const store =  new Vuex.Store({
        state: {
            count: 0
        },
        mutations: {
            incrementMutations(state) {
            	return state.count++
            }
        },
            
        actions: {
            incrementActions({commit}) {
            	commit("incrementMutations"); 
            }
         
        },
        
        //通过getter中的方法来获取state值
        getters: {
            getCount(state) {
            	return state.count
            }
        }
        })
         
        export default store

main.js

        import Vue from 'vue'
        import App from './App.vue'
        import store from './store'
         
        Vue.config.productionTip = false
         
        new Vue({
          store,
          render: h => h(App)
        }).$mount('#app')

APP.store

       <template>
       <div id="app">
           <div id="app">
               <button @click="incrementClick">增加</button>
               {{this.$store.getters.getCount}}
           </div>
       </div>
       </template>
        
       <script>
       export default {
           methods: {
             incrementClick(){
               this.$store.dispatch("incrementActions")
             }
           }
       }
       </script>

参考文章