vuex介绍和五个模块

君哥 阅读:1515 2020-01-06 11:37:28 评论:1

1.为什么需要学习vuex这样一个技术解决方案?

vuex主要解决的问题就是在复杂的组件关系情况下,组件之间的数据如何更加便捷的进行传递。


2.vuex要学习什么东西?

学习vuex最重要的就是要学习五个核心模块的使用方式,使用他们来实现数据存储,数据传递。

五个核心模块分别是:state,mutations,actions,modules,getters


3.state有什么用?state是如何使用的?

state是用来存储数据的地方,我们需要传递的数据或者需要保存的数据都会在state中声明。


state的使用方式:

A. 原始形式: $store.state.变量名称

B. 辅助函数: import { mapState } from 'vuex'

computed:{

     ...mapState(['变量名称'])

}


4.mutations有什么用?是如何使用的?

mutations提供了一系列方法对state中的数据进行修改,必须使用mutations来修改state中的数据,不要直接修改state中的数据。


使用方式:

A. 原始形式: $store.commit('方法名称',参数数据)

B. 辅助函数: import { mapMutations } from 'vuex'

methods:{

     ...mapMutations(['方法名称'])

}


5. actions有什么用?如何使用?

actions专门设置一些需要处理异步操作(发送请求)的方法的模块


使用方式:

A. 原始形式: $store.dispatch('方法名称',参数数据)

B. 辅助函数: import { mapActions } from 'vuex'

methods:{

     ...mapActions(['方法名称'])

}


6. getters有什么用?如何使用?

类似于Vue中的计算属性,getters可以对vuex中的数据进行处理,返回用户需要的数据内容。


使用方式:

A. 原始形式: $store.getters.方法名

B. 辅助函数: import { mapGetters } from 'vuex'

computed:{

     ...mapGetters(['方法名称'])

}


7. modules可以帮助我们进行模块化处理,当我们添加设置了子模块之后,要如何访问子模块中的state,mutations,actions内容呢?

注意:如果要进行模块化的处理,要求子模块必须添加 namespaced:true。


假设有子模块users,users中有数据age,有修改age数据的setAge方法,还有异步请求获取数据 getAge方法


created(){

    this.$store.dispatch('users/getAge')

},

methods:{

    fn(){

        this.$store.commit('users/setAge', 20)

        console.log( this.$store.state.users.age )

    }

}


本文链接:https://www.yanjun202.com/post/46.html 

分享到:
可以去百度分享获取分享代码输入这里。
发表评论
搜索
关注我们

扫一扫关注我们,了解最新精彩内容