Vue 状态集中管理vuex

1、store ==>index.js

import Vue from 'vue'

import Vuex from 'vuex'

 

import types from './types'  mutations的函数名放在这个文件里

import taskManage from './modules/taskManage'

 

Vue.use(Vuex);

 

export default new Vuex.Store({

  types,

  modules: {

    taskManage

  },

});

 

2、main.js

import Vue from 'vue';

import App from './App.vue';

import store from './store';

 

new Vue({

  store,

  render: h => h(App),

}).$mount('#app');

3、types.js // mutations的函数名放在这个文件里,可有可无 

export const SET_INFO = 'SET_INFO'

4、modules ==> taskManage.js // 主要逻辑写这

import {  SET_INFO } from '../types'

import { getInfo } from '@api' // 数据接口

// vuex中的数据源,我们需要保存的数据就保存在这里,可以在页面通过 this.$store.state来获取我们定义的数据;

const state = { 

  userInfo: {}

}

// Getter相当于computed计算属性,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算,Getters 可以用于监听、state中的值的变化,返回计算后的结果

const getters = {

  userInfo: state => state.userInfo

}

// Action 类似于 mutation,不同在于:

    1.Action 提交的是 mutation,而不是直接变更状态。 

    2.Action 可以包含任意异步操作

const actions = { // 可以将传进来的参数在传给mutations(可选)

  async getUserInfo({ commit }, params) { // 调用接口处理数据

    const data = await getInfo (params)

    commit(SET_INFO, data)

    return data

  },

}

// Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数(handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数,payload作为第二个参数(额外的参数) 必须是同步函数

const mutations = { // 第一个就是store.state,第二个是外部传进来的参数(可选)

  [SET_INFO](state, res) {

    state.userInfo= res? res: {}

  },

}

 

export default {

  state,

  getters,

  actions,

  mutations

}

5、 taskManage.js 页面调用

import { mapActions, mapGetters } from "vuex"

computed: {

      ...mapGetters([

        "userInfo",  // 数据状态值

      ]),

    },

methods: {

      ...mapActions([

        "getUserInfo", // 调方法

      ]),

    // 获取用户信息

      handleUserInfo(id) {

        let param = { id: id }

        this.getUserInfo(param).then(res => {

          console.warn(res )

        })

        

      },

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小小并不小

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值