- vuex是什么?
vue官方解释:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。 - vuex的组成部分
state (状态)
action (动作,业务交互)
mutation (修改state)
getter (获取数据的) - vuex的安装
直接下载/CDN
https://unpkg.com/vuex
NPM
YARNnpm/cnpm install vuex --save # If using vue 3.0 + vuex 4.0; npm/cnpm install vuex@next --save
yarn add vuex # If using Vue 3.0 + Vuex 4.0: yarn add vuex@next --save
- 使用
在store文件夹index.js
在组件中取得vuex中获取到的值export default new Vuex.Store({ state: { banner: null }, action: { getBanner ({commit}){ let result = axios({ url: url,//路径 method: 'get', params: {//请求参数} }) let action = { type: 'bannerType', payload: result } commit( action ) } }, mutations: { bannerType( state, action ) { state.banner = action.payload.data //修改state中的banner值,将action中请求到的值赋给state中的banner }, }, getters: { getBanners ( state ) { return state.banner //最后获取到的banner值 }, } })
import {mapActions, mapGetters} from 'vuex'; //mapActions, mapGetters是vuex中的辅助函数 export default{ data() { return{ banner: '' } }, methods: { ...mapActions(['getBanner']), }, computed(){ ...mapGetters(['getBanners']) }, async created(){ await this.getBanner() this.banner = this.getBanners?this.getBanners:'' } }
vue中vuex的使用
最新推荐文章于 2022-08-17 09:28:08 发布