• 153-Vue中的vuex内的辅助函数——mapState,mapGetters,mapMutations,mapActions的用法


    153-Vue中的vuex内的辅助函数——mapState,mapGetters,mapMutations,mapActions的用法

    首先查看目录:

     

    此文章所涉及到的代码:src/components/Comp1.vue

    store/index.js

    views/HomeView.vue

    其它的都是初建的代码,未做改动,此处不展示。

    Comp1.vue代码如下:

    1. <template>
    2. <div>
    3. <p>{{num}}p>
    4. <p>{{title}}p>
    5. <p>{{dbNum}}p>
    6. <button @click="chanNum(1)">同步按钮button>
    7. <button @click="asyncChanNum(100)">异步按钮button>
    8. div>
    9. template>
    10. <script>
    11. import { mapMutations, mapState,mapActions,mapGetters } from 'vuex'
    12. export default {
    13. methods:{
    14. ...mapMutations(['chanNum']), // 同步
    15. // add(){
    16. // this.$store.commit('chanNum',10)
    17. // },
    18. ...mapActions(['asyncChanNum']), // 异步
    19. // add1(){
    20. // this.$store.dispatch('asyncChanNum',100)
    21. // }
    22. },
    23. computed:{
    24. ...mapState(['num','title']),
    25. // num(){
    26. // return this.$store.state.num
    27. // }
    28. ...mapGetters(['dbNum']),
    29. // dbNum(){
    30. // return this.$store.getters.dbNum
    31. // }
    32. },
    33. data () {
    34. return {
    35. }
    36. }
    37. }
    38. script>
    39. <style lang = "less" scoped>
    40. style>

     store/index.js代码如下:

    1. import Vue from 'vue'
    2. import Vuex from 'vuex'
    3. Vue.use(Vuex)
    4. export default new Vuex.Store({
    5. state: {
    6. num:11,
    7. title:'标题'
    8. },
    9. getters: {
    10. dbNum(state){
    11. return state.num*2
    12. }
    13. },
    14. mutations: { // 同步
    15. chanNum(state,payload){
    16. state.num+=payload
    17. }
    18. },
    19. actions: { // 异步
    20. asyncChanNum({commit},payload){
    21. setTimeout(()=>{
    22. commit('chanNum',payload)
    23. },1000)
    24. }
    25. },
    26. modules: {
    27. }
    28. })

    views/HomeView.vue代码如下:

    1. <template>
    2. <div class="home">
    3. <HelloWorld />
    4. div>
    5. template>
    6. <script>
    7. // @ is an alias to /src
    8. import HelloWorld from '@/components/Comp1.vue'
    9. export default {
    10. name: 'HomeView',
    11. components: {
    12. HelloWorld
    13. }
    14. }
    15. script>

    下面显示操作步骤:

    最终效果如下:

     

     

  • 相关阅读:
    SpringBoot死信队列、延迟队列
    合肥大厂校招
    区块链技术与应用 - 学习笔记1【引言】
    前端发布项目后,解决缓存的老版本文件问题
    环境配置|GitHub——如何在github上搭建自己写的网站
    深入线程同步
    Pytorch指定数据加载器使用子进程
    请使用java完成以下实验
    Python经典习题(一)
    java高级阶段的总结
  • 原文地址:https://blog.csdn.net/jolinoy/article/details/126288671