一、什么是vuex
vuex是在vue项目中实现数据共享的框架。用于当多个组件进行复杂的数据传值很困难的时候。这时将某个数据放在公共的存储空间去存储, 当某一个组件改变这个公共的数组,所有其他引用这个数据的组件能够动态感知到。
官网: https://vuex.vuejs.org/zh/

二、怎么用
1.安装
npm install vuex --save
2.引入
import Vuex from 'vuex'
3.新建一个store目录,用于存放vuex数据。
新建 store/index.js

在入口文件中引入store

使用的时候

因为在main.js(全局中注册)中使用了store,因此store里的数据会被派发到各个组件中。
三、怎么修改
1.dispatch一个actions。一个参数是派发actions的名字,第二个是要传的数据。

2.在store中创建一个跟派发actions名字(changeCity)相同的action。一个参数是上下文ctx,第二是传过来的数据city

3.actions需要commit mutations

四、如果没有复杂业务逻辑,可以通过组件直接调用mutations

五、mapState
mapState是将vuex中state数据映射到组件中,在computed计算属性中,将state中的city数据,自定义命名为currentCity

使用的时候

六、mapMutations
使用:不用写成绿框中的内容了,直接写成this.changeCity(city)即可

网友评论