初识vue第六篇

本文详细介绍了Vuex,一个用于Vue应用状态管理的工具,包括其作为插件的作用、应用场景、优势以及如何创建、使用和管理store、mutations、actions和getters。还涉及了模块化的概念,以提高大型应用的可维护性。
摘要由CSDN通过智能技术生成

vuex

1. 是什么:
① vuex 是一个 vue 的 状态管理工具,状态就是数据。
② vuex 是一个插件,可以帮我们管理 vue 通用的数据 (多组件共享的数据)
2. 场景:
① 某个状态 在 很多个组件 来使用 (个人信息)
② 多个组件 共同维护 一份数据 (购物车)
3. 优势:
① 共同维护一份数据,数据集中化管理
② 响应式变化
③ 操作简洁 (vuex提供了一些辅助函数)

创建一个空仓库

1.目标:

安装 vuex 插件,初始化一个空仓库

2.步骤

安安装安装 vuexvuex装 v安装 vuexuex

state 状态 

1. 提供数据:
State 提供唯一的公共数据源,所有共享的数据都要统一放到 Store 中的 State 中存储。
在 state 对象中可以添加我们要共享的数据。
// 创建仓库
const store = new Vuex.Store({
// state 状态, 即数据, 类似于vue组件中的data
// 区别:
// 1. data 是组件自己的数据
// 2. state 是所有组件共享的数据
state: {
count: 101
}
})
2. 使用数据:
① 通过 store 直接访问
② 通过辅助函数
获取 store:
(1) this.$store
(2) import 导入 store
模板中: {{ $store.state.xxx }}
组件逻辑中: this.$store.state.xxx
JS模块中: store.state.xxx

mutations

1. 定义 mutations 对象,对象中存放修改 state 的方法
const store = new Vuex.Store({
    state: {
        count: 0
    },
// 定义mutations
    mutations: {
// 第一个参数是当前store的state属性
        addCount (state) {
            state.count += 1
        }
    }
})
2. 组件中提交调用 mutations
this.$store.commit('addCount')
3.辅助函数 - mapMutations
mapMutations 和 mapState很像,它是把位于mutations中的方法提取了出来,映射到组件methods中
mutations: {
    subCount (state, n) {
        state.count -= n
    },
}
import { mapMutations } from 'vuex'
    methods: {
    ...mapMutations(['subCount'])
}


methods: {
    subCount (n) {
        this.$store.commit('subCount', n)
    },
}

actions

1. 提供action 方法
actions: {
    setAsyncCount (context, num) {
        // 一秒后, 给一个数, 去修改 num
        setTimeout(() => {
            context.commit('changeCount', num)
        }, 1000)
    }
}
2. 页面中 dispatch 调用
this.$store.dispatch('setAsyncCount', 200)

getters

1. 定义 getters
getters: {
// 注意:
// (1) getters函数的第一个参数是 state
// (2) getters函数必须要有返回值
    filterList (state) {
        return state.list.filter(item => item > 5)
    }
}
2. 访问getters
① 通过 store 访问 getters
{{ $store.getters.filterList }}
② 通过辅助函数 mapGetters 映射
computed: {
...mapGetters(['filterList'])
},
{{ filterList }}

模块 module (进阶语法)

由于 vuex 使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,
store 对象就有可能变得相当臃肿。(当项目变得越来越大的时候,Vuex会变得越来越难以维护)
//模块拆分:
const state = {
    userInfo: {
    name: 'zs',
    age: 18
}
}
const mutations = {}
const actions = {}
const getters = {}
export default {
    state,
    mutations,
    actions,
    getters
}
user模块: store/modules/user.js

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值