vue之状态管理器
作者:互联网
store.js
import axios from '@/utils/request' export default { state: { // 首页需要的初始化数据 bannerlist: [], prolist: [] }, getters: { // state的计算属性 }, actions: { // 当前页面需要的异步操作 getBannerlist (context) { // 请求轮播图数据,context上下文对象 axios.get('/banner').then(res => { context.commit({ // 唯一改变状态管理器的方式就是显示的提交mutation type: 'changeBannerlist', data: res.data.data }) }) }, getProlist ({ commit }) { // 参数解构 axios.get('/pro').then(res => { commit({ type: 'changeProlist', data: res.data.data }) }) } }, mutations: { changeBannerlist (state, data) { state.bannerlist = data.data }, changeProlist (state, data) { state.prolist = data.data } } }
index.vue
<template> <div class="box"> <header class="header"> <router-link to="/search">搜索</router-link> </header> <div class="content" id="content"> <!-- 轮播图 --> <van-swipe :autoplay="4000" indicator-color="white"> <van-swipe-item v-for="item of bannerlist" :key="item.bannerid"> <img :src="item.img" alt=""> </van-swipe-item> </van-swipe> <Prolist :prolist="prolist" /> </div> </div> </template> <script> import Vue from 'vue' import { Swipe, SwipeItem } from 'vant' import { mapState } from 'vuex' import Prolist from '@/components/Prolist' Vue.use(Swipe).use(SwipeItem) export default { components: { Prolist }, computed: { // 使用组件的计算属性获取状态管理器中的数据,具有依赖性 ...mapState({ // 获取状态管理器中的数据 bannerlist: (state) => { // 默认参数为state ---- 所有的状态state console.log(state) // { home: {}, kind: {}, cart: {}} return state.home.bannerlist }, // prolist: ({ home }) => home.prolist prolist: ({ home: { prolist } }) => prolist }) }, created () { // 触发状态管理器中的actions this.$store.dispatch('getBannerlist') this.$store.dispatch('getProlist') } } </script> <style lang="scss"> .van-swipe { // height: 180px; img { width: 100%; } } .backtop { position: fixed; bottom: 60px; right: 10px; font-size: 30px; } </style>
标签:状态,vue,管理器,state,prolist,import,home,data 来源: https://www.cnblogs.com/hy96/p/12063902.html