zoukankan      html  css  js  c++  java
  • VueX 的安装及简单使用

    1、安装vuex依赖包

    npm install vuex --save

    2、导入vuex包

    import Vuex from 'vuex'
    Vue.use(Vuex)

    3、创建 store 对象

    export default new Vuex.Store({
      // state 中存放的就是全局共享的数据
      state: {
        count: 0
      }
    })

    4、将 store 对象挂载到 vue 实例中

    new Vue({
      el: '#app',
      render: h => h(App),
      router,
      // 将创建的共享数据对象,挂载到 Vue 实例中
      // 所有的组件,就可以直接用 store 中获取全局的数据了
      store
    })

    Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

    核心模块:State、Mutations、Actions、Module、Getters

    在 components 目录下新建 Addition.vue 文件:

    <template>
    <div>
      <h3>当前最新的Count值为:</h3>
      <button>+1</button>
    </div>
    </template>

    Subtraction.vue 文件:

    <template>
    <div>
      <h3>当前最新的Count值为:</h3>
      <button>-1</button>
    </div>
    </template>

    打开 App.vue 文件,引入俩个组件:

    <template>
    <div>
      <my-addition></my-addition>
      <p>------------------------------</p>
      <my-subtraction></my-subtraction>
    </div>
    </template>
    
    <script>
    import Addition from './components/Addition'
    import Subtraction from './components/Subtraction'
    export default {
      components: {
        'my-addition': Addition,
        'my-subtraction': Subtraction
      },
      data () {
        return {}
      }
    }
    </script>

    (1)、State:

    State 提供唯一的公告数据源,所有共享的数据都要统一放到 Store 的 State 中进行存储。我们需要保存的数据就保存在这里,可以在页面通过 this.$store.state来获取我们定义的数据。
    // 创建store数据源,提供唯一公共数据
    const store = new Vuex.Store({
       state: {
          count: 0
       }
    })

    组件访问 Store 中数据的第一种方式:

    this.$store.state.全局数据名称

    组件访问 Store 中数据的第二种方式:

    // 1.从 vuex 中按需导入 mapState 函数
    import { mapState } from 'vuex'

    通过刚才导入的 mapState 函数,将当前组件需要的全局数据,映射为当前组件的 computed 计算属性:

    // 2.将全局数据,映射为当前组件的计算属性
    computed: {
        ...mapState(['count'])
    }

    打开 store/index.js 文件,定义 count:

    import Vue from 'vue'
    import Vuex from 'vuex'
    
    Vue.use(Vuex)
    
    export default new Vuex.Store({
      state: {
        count: 0
      },
      mutations: {
      },
      actions: {
      },
      modules: {
      }
    })

    回到 Addition.vue 文件中,用第一种方式:

    <template>
    <div>
      <h3>当前最新的Count值为:{{$store.state.count}}</h3>
      <button @click="handleAdd">+1</button>
    </div>
    </template>

    回到 Subtraction.vue 文件中,用第二种方式:

    <template>
    <div>
      <h3>当前最新的Count值为:{{count}}</h3>
      <button>-1</button>
    </div>
    </template>
    
    <script>
    import { mapState } from 'vuex'
    export default {
      data () {
        return {}
      },
      // 计算属性
      computed: {
        ...mapState(['count']) // 用...展开运算符把Count展开在资源属性里
      }
    }
    </script>

    此时效果图:

    (2)、Mutations:

    Mutations 用于变更 Store 中的数据。只有 mutation 里的函数才有权利去修改 state 中的数据。mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。但是,mutation只允许同步函数,不能写异步的代码

    ①只能通过 mutation 变更 Store 数据,不可以直接操作 Store 中的数据。
    ②通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化。

    定义:

    // 定义 Mutation
    const store = new Vuex.Store({
      state: {
        count: 0
      },
      mutations: {
        add (state) {
          // 变更状态
          state.count++
        }
      }
    })

    第一种触发方式:

    // 触发 mutation
    methods: {
        handleAdd () {
          // 触发 mutations 的第一种方式
          this.$store.commit('add')
        }
    }

    打开 store/index.js 文件,定义 mutations :

    mutations: {
        add (state) {
          state.count++
        }
    }

    回到 Addition.vue 文件中触发:

    <template>
    <div>
      <h3>当前最新的Count值为:{{$store.state.count}}</h3>
      <button @click="handleAdd">+1</button>
    </div>
    </template>
    
    <script>
    export default {
      methods: {
        handleAdd () {
          this.$store.commit('add')
        }
      }
    }
    </script>

    此时点击+1按钮,就可以看到数值变为1。

    还可以在触发 mutations 时传递参数:

    // 定义 Mutation
    const store = new Vuex.Store({
      state: {
        count: 0
      },
      mutations: {
        addN (state, step) {
          // 变更状态
          state.count += step
        }
      }
    })

    第一种触发方式:

    // 触发 mutation
    methods: {
        handleAdd () {
          this.$store.commit('addN', 3)
        }
    }

    打开 store/index.js 文件,增加一个 addN: 

    mutations: {
        add (state) {
          state.count++
        },
        addN (state, step) {
          state.count += step
        }
    }

    回到 Addition.vue 文件中,增加一个+N的按钮并增加点击事件:

    <template>
    <div>
      <h3>当前最新的Count值为:{{$store.state.count}}</h3>
      <button @click="handleAdd">+1</button>
      <button @click="handleAdd2">+N</button>
    </div>
    </template>
    
    <script>
    export default {
      data () {
        return {
          num: 2
        }
      },
      methods: {
        handleAdd () {
          this.$store.commit('add')
        },
        handleAdd2 () {
          // commit 的作用,就是调用某个 mutation 函数
          this.$store.commit('addN', this.num)
        }
      }
    }
    </script>

    此时点击+N按钮就会每次增加2。

    触发 mutations 的第二种方式:

    // 1.从 vuex 中按需导入 mapMutations 函数
    import { mapMutations } from 'vuex'

    通过刚才导入的 mapMutations 函数,将需要的 mutations 函数,映射为当前组件的 methods 方法:

    // 2.将指定的 mutations 函数,映射为当前组件的methods 函数:
    methods: {
       ...mapMutations({'add', 'addN'})
    }

    打开 store/index.js 文件,在 mutations 增加一个 sub:

    mutations: {
        add (state) {
          state.count++
        },
        addN (state, step) {
          state.count += step
        },
        sub (state) {
          state.count--
        }
    },

    回到 Subtraction.vue 文件中,给-1按钮增加点击事件:

    <template>
    <div>
      <h3>当前最新的Count值为:{{count}}</h3>
      <button @click="handleSub">-1</button>
    </div>
    </template>
    
    <script>
    import { mapState, mapMutations } from 'vuex'
    export default {
      data () {
        return {}
      },
      // 计算属性
      computed: {
        ...mapState(['count']) // 用...展开运算符把Count展开在资源属性里
      },
      methods: {
        ...mapMutations(['sub']),
        handleSub () {
          this.sub()
        }
      }
    }
    </script>

    这时刷新页面,点击-1按钮就会每次-1了。

    打开 store/index.js 文件,增加一个 subN: 

    mutations: {
        add (state) {
          state.count++
        },
        addN (state, step) {
          state.count += step
        },
        sub (state) {
          state.count--
        },
        subN (state, step) {
          state.count -= step
        }
    },

    回到 Subtraction.vue 文件中,在增加一个-N的按钮,并添加点击事件:

    <button @click="handleSub2">-N</button>
    
    <script>
    import { mapState, mapMutations } from 'vuex'
    export default {
      methods: {
        ...mapMutations(['sub', 'subN']),
        handleSub () {
          this.sub()
        },
        handleSub2 () {
          this.subN(2)
        }
      }
    }
    </script>

    这时点击-N按钮,每次就-2了。

    下面有个需求,就是在点击+1按钮后延迟1秒在显示变化后的数值。

    注意:不要在 mutations 函数中,执行异步操作。所以就需要用到了 Action 用于处理异步任务。

    (3)、Actions:

    Action 用于处理异步任务。

    如果通过异步操作变更数据,必须通过 Action,但是在 Action 中还是要通过触发 Mutation 的方式间接变更数据。

    定义:

    // 定义 Action
    const store = new Vuex.Store({
      // ...省略其他代码
      mutations: {
        add (state) {
          state.count++
        }
      },
      actions: {
        addAsync (context) {
          setTimeout(() => {
            context.commit('add')
          }, 1000)
        }
      }
    })

    第一种方式触发:

    // 触发 Action
    methods: {
      handleAdd () {
          // 触发 actions 的第一种方式
          this.$store.dispatch('addAsync')
      }
    }

    打开 store/index.js 文件,增加一个 addAsync: 

    actions: {
        addAsync (context) {
          setTimeout(() => {
            // 在 actions 中,不能直接修改 state 中的数据
            // 必须通过 context.commit() 触发某个 mutations 的函数才行
            context.commit('add')
          }, 1000)
        }
    }

    回到 Addition.vue 文件中,增加一个+1 Async的按钮并增加点击事件:

     <button @click="handleAdd3">+1 Async</button>
    
    <script>
    export default {
      methods: {
        handleAdd () {
          this.$store.commit('add')
        },
        handleAdd2 () {
          // commit 的作用,就是调用某个 mutation 函数
          this.$store.commit('addN', this.num)
        },
        handleAdd3 () {
          this.$store.dispatch('addAsync')
        }
      }
    }
    </script>

    这时点击+1 Async按钮,可以实现延迟1秒后+1的功能了。

    触发 actions 异步任务时携带参数:

    定义:

    // 定义 Action
    const store = new Vuex.Store({
      // ...省略其他代码
      mutations: {
        addN (state, step) {
          state.count += step
        },
      },
      actions: {
        addNAsync (context, step) {
          setTimeout(() => {
            context.commit('addN', step)
          }, 1000)
        }
      }
    })

    触发:

    // 触发 Action
    methods: {
      handleAdd () {
          // 在调用 dispatch 函数,触发 actions 时携带参数
          this.$store.dispatch('addNAsync', 5)
      }
    }

    打开 store/index.js 文件,增加一个 addNAsync: 

    actions: {
        addAsync (context) {
          setTimeout(() => {
            // 在 actions 中,不能直接修改 state 中的数据
            // 必须通过 context.commit() 触发某个 mutations 的函数才行
            context.commit('add')
          }, 1000)
        },
        addNAsync (context, step) {
          setTimeout(() => {
            context.commit('addN', step)
          }, 1000)
        }
    }

    回到 Addition.vue 文件中,增加一个+N Async的按钮并增加点击事件:

    <button @click="handleAdd4">+N Async</button>
    
    <script>
    export default {
      methods: {
        handleAdd4 () {
          // 在调用 dispatch 函数,触发 actions 时携带参数
          this.$store.dispatch('addNAsync', 5)
        }
      }
    }
    </script>

    这时点击+N Async按钮,可以实现延迟1秒后+5的功能。

    触发 actions 的第二种方式:

    // 1.从 vuex 中按需导入 mapActions 函数
    import { mapActions } from 'vuex'

    通过刚才导入的 mapActions 函数,将需要的 actions 函数,映射为当前组件的 methods 方法:

    // 2.将指定的 actions 函数,映射为当前组件的 methods 函数
    methods: {
      ...mapActions(['addAsync', 'addNAsync'])
    }

    打开 store/index.js 文件,在 actions 增加一个 subAsync:

    actions: {
        addAsync (context) {
          setTimeout(() => {
            // 在 actions 中,不能直接修改 state 中的数据
            // 必须通过 context.commit() 触发某个 mutations 的函数才行
            context.commit('add')
          }, 1000)
        },
        addNAsync (context, step) {
          setTimeout(() => {
            context.commit('addN', step)
          }, 1000)
        },
        subAsync (context) {
          setTimeout(() => {
            context.commit('sub')
          }, 1000)
        }
    }

    回到 Subtraction.vue 文件中,在增加一个-1 Async的按钮,并添加点击事件:

    <button @click="handleSub3">-1 Async</button>
    
    <script>
    import { mapState, mapMutations, mapActions } from 'vuex'
    export default {
      methods: {
        ...mapMutations(['sub', 'subN']),
        ...mapActions(['subAsync']),
        handleSub () {
          this.sub()
        },
        handleSub2 () {
          this.subN(2)
        },
        handleSub3 () {
          this.subAsync()
        }
      }
    }
    </script>

    还有个更简单的方式:

    <button @click="subAsync">-1 Async</button>
    
    <script>
    import { mapState, mapMutations, mapActions } from 'vuex'
    export default {
      methods: {
        ...mapActions(['subAsync'])
      }
    }
    </script>

    这样实现的效果是一样的。

    下面用同样的思路来实现-N的异步操作:

    打开 store/index.js 文件,增加一个 subNAsync: 

    actions: {
        subNAsync (context, step) {
          setTimeout(() => {
            context.commit('subN', step)
          }, 1000)
        }
    }

    回到 Subtraction.vue 文件中,在增加一个-N Async的按钮:

    <button @click="subNAsync(3)">-N Async</button>
    
    <script>
    import { mapState, mapMutations, mapActions } from 'vuex'
    export default {
      methods: {
        ...mapActions(['subAsync', 'subNAsync'])
      }
    }
    </script>

    这时点击-N Async按钮,可以实现延迟1秒后-3的功能。

    (4)、Getters:

    Getter 用于对 Store 中的数据进行加工处理形成新的数据。不会修改 state 里的源数据,只起到一个包装器的作用,将 state 里的数据变一种形式然后返回出来。
    ① Getter 可以对 Store 中已有的数据加工处理之后形成新的数据,类似Vue的计算属性。
    ② Store 中数据发生变化,Getter 包装出来的数据也会跟着变化。

    定义:

    // 定义 Getter
    const store = new Vuex.Store({
      state: {
        count: 0
      },
      getters: {
        showNum: state => {
          return '当前最新的数量是【'+ state.count +'】'
        }
      }
    })

    使用 getters 的第一种方式:

    this.$store.getters.名称

    我们可以把文字的内容删除掉,然后用 getters 来替换:

    打开 store/index.js 文件,定义getters:

    getters: {
        showNum (state) {
          return '当前最新的数量是【' + state.count + '】'
        }
    }

    回到 Addition.vue 文件修改:

    <h3>{{$store.getters.showNum}}</h3>

    此时刷新页面,已经变为了 getters 中的内容,效果图:

    使用 getters 的第二种方式:

    import { mapGetters } from 'vuex'
    
    computed: {
      ...mapGetters(['showNum'])
    }

    打开 Subtraction.vue 文件修改:

    <h3>{{showNum}}</h3>
    
    <script>
    import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
    export default {
      // 计算属性
      computed: {
        ...mapState(['count']), // 用...展开运算符把Count展开在资源属性里
        ...mapGetters(['showNum'])
      }
    }
    </script>

    效果图:

  • 相关阅读:
    C++快速排序
    C++冒泡排序
    为什么Excel创建一个新的工作簿就会初始化三个worksheet
    为什么游戏需要英雄
    2015.11.18——Lua中文教程
    [国家集训队2012]JZPFAR
    后缀数组小结?
    [BZOJ 2738]矩阵乘法
    [BZOJ 3221][Codechef FEB13] Obserbing the tree树上询问
    [BZOJ 4999]This Problem Is Too Simple!
  • 原文地址:https://www.cnblogs.com/joe235/p/12801812.html
Copyright © 2011-2022 走看看