脚手架选择vuex
或者手动下载vuex -> 单独创建store.js 引入vuex -> new Vuex.Store({state: {},mutations: {},actions: {}})
1.引用state公共数据的两种方式 (组件computed中)
在需要使用的组件中this.$store.state.数据名 //模板使用的时候不用带this
在需要使用的组件中import { mapState } from 'vuex'导入 -> 在computed里...mapState(['数据名']) 展开 作为属性使用
2.store.js中的方法总管mutations (组件methods中)
组件不能私自修改store数据
2.1通过this.$store.commit('仓库定义的方法') -> 仓库mutations中 '对应组件方法'(state){ state.数据名//获取数据操作 }
携带参数 this.$store.commit('仓库定义的方法',参数) 仓库方法有形参接收
2.2组件引入import {mapMutations} from 'vuex' -> 在组件methods里...mapMutations(['仓库方法名']) 组件定义一个方法调用this.仓库名方法() //或者直接在模板事件后面直接写导入的仓库方法名,有参数带在括号后
携带参数 组件定义方法(){ this.仓库名方法(参数) } //参数在仓库方法中必须有对应的形参接收
3.action处理异步 (组件methods中)
// 在actions中,不能直接修改state中的数据
// 必须通过context.commit() 触发某个mutation才行
组件里在methods用this.$store.dispatch('store中action的方法名',参数) -> store里action在context.commit('mutations中的方法',参数)
另外一种方式是import { mapAction } from 'vuex' -> 在methods中...mapAction(['仓库异步方法名'])
4.getters 过滤 相当于computed (组件computed中)
方式1:在组件里{{$store.getters.方法名}}
方式2:在组件里import { mapGetters } from 'vuex' -> computed里...mapGetters(['方法名']) 调用{{方法名}}
vuex的使用
最新推荐文章于 2022-11-23 10:37:00 发布