• Vuex---对Vuex的理解与使用~~~


    一。原理分析

    使用场景:共享

    1。多个组件依赖于同一个状态(数据)。

    2.来自不同组件的行为需要变更同一状态。

    在 Actions  中发送ajax请求。

    Vuex中有三个东西:Actions、Mutations、State,这些都被store管理着。

    允许直接commit到Motations。

    二。使用Vuex

    1.创建src/store/index.js文件:

    作用:初始化数据、配置actions、配置mutations

    1. // 该文件用于创建Vuex中最为核心的store
    2. // 引入Vuex
    3. import Vuex from 'vuex'
    4. import Vue from 'vue'
    5. // 准备actions---用于响应组件中的动作
    6. const actions ={
    7. // jia:function(){
    8. // console.log("actions中的jia被调用了");
    9. // }
    10. jia(context,value){
    11. console.log("actions中的jia被调用了");
    12. context.commit("JIA",value)
    13. },
    14. jian(context,value){
    15. console.log("actions中的jian被调用了");
    16. context.commit("JIAN",value)
    17. },
    18. // 当sum为奇数的时候在 加
    19. jiaOdd(context,value){
    20. console.log("actions中的jiaOdd被调用了");
    21. if(context.state.sum % 2){
    22. context.commit("JIA",value)
    23. }
    24. },
    25. // 等一等再加
    26. jiaWait(context,value){
    27. console.log("actions中的jiaWait被调用了");
    28. setTimeout(()=>{
    29. context.commit("JIA",value)
    30. },500)
    31. },
    32. }
    33. // 准备mutations--用于操作数据(state)
    34. const mutations = {
    35. JIA(state,value){
    36. console.log("mutations中的JIA被调用了");
    37. state.sum += value;
    38. },
    39. JIAN(state,value){
    40. console.log("mutations中的JIAN被调用了");
    41. state.sum -= value;
    42. }
    43. }
    44. // 准备state---用于存储数据
    45. const state = {
    46. sum:0 //用于求和:当前的和
    47. }
    48. // 准备getters--用于将state中的数据进行加工
    49. const getters ={
    50. bigSum(state){
    51. return state.sum *10;
    52. }
    53. }
    54. Vue.use(Vuex)
    55. // 创建store
    56. const store = new Vuex.store({
    57. actions:actions,
    58. mutations:mutations,
    59. state:state,
    60. getters,
    61. })
    62. // 暴露store
    63. export default store

    2. 在main.js中,创建vm时传入store配置项:

     

    3. 在组件中读取Vuex中的数据:

     4.组件中修改Vuex中的数据:

     5.getters的使用:

    使用场景:当state中的数据需要经过加工后再使用时,再getters中进行加工。

    1)再src/store/index.js中:

     2)在组件中读取getters中的数据:

     二。mapState方法和mapGetters方法

    1)mapState方法:用于帮助我们映射state中的数据为计算属性。

     2)mapGetters方法:用于帮助我们映射getters中的数据为计算属性。

  • 相关阅读:
    【软考软件评测师】第二十九章 可靠性可用性测试
    22 年最全面试java八股文合集
    青少年python系列 28.turtle库绘一个圆点
    SaaSBase:什么是CDP集团?
    来啦来啦|开源 * 安全 * 赋能 - .NET Conf China 2022
    新手必会的静态站点生成器——Gridsome
    RxJava(三)-合并操作符
    python astra相机驱动问题
    【Spring Cloud实战】Eurake服务注册与发现
    Mac 本地部署thinkphp8【部署环境以及下载thinkphp】
  • 原文地址:https://blog.csdn.net/weixin_57375608/article/details/127450041