Vuex管理工具

vuex管理工具

主要功能

1、vuex可以实现vue不同组件之间的状态共享(解决不同组件之间的数据共享)
2、可以实现组件里面数据的持久化

vuex的几个核心概念
  1. State: 定义数据
  2. Getters:就像计算属性一样,getter的返回值会跟你局它的依赖被缓存起来,且只有当它的依赖值放生改变的时候才会被重新计算。
  3. Mutations:定义方法
  4. Actions:action提交的是mutation,而不是直接变更数据状态,action可以包含任意异步操作。
  5. Miodules:分割模块
1.简单使用方法 main.js
import { createApp } from 'vue'
import App from './App.vue'
import store from './vuex/store'

const app = createApp(App)

app.use(store)

app.mount('#app')

2.封装体 store.js
import { createStore } from 'vuex'
import containerStore from "./ContainerStore";
// Create a new store instance.
const store = createStore({
    modules:{
      'containerStore':containerStore
    },
    state () { //定义数据
        return {
            count: 0,
            msg:'你好getters方法!!!!1234'
        }
    },
    mutations: { //定义方法
        increment (state) {
            setTimeout(()=>{
                state.count++
            },1000)

        },
        setCount(state,step){
            state.count = state.count + step
        }
    },
    getters:{//计算属性
        reverseMsg(state){
            return state.msg.substr(0,state.msg.length - 1).concat(state.count)
        }
    },
    actions:{//异步操作  执行 mutations 里面的方法
        incCount(context){
            context.commit('increment')
        }
    }
})

export  default  store

3.使用方法header.vue
<template>
    <div>
        header
        <p>{{count}}</p>
        <p>{{reverseMsg}}</p>
        <button @click="add">点我</button>
        <button @click="addAction">mapActions</button>
        <p></p>
        <Container></Container>

    </div>
</template>

<script>

    import Container from "./Container";
    import {mapState, mapGetters,mapActions} from 'vuex'

    export default {
        name: "Header",
        components: {Container},
        data() {
            return {}
        },
        methods: {
            add() {
                //执行方法
                // this.$store.commit('increment')
                //this.$store.commit('setCount', 10)
            },
            addAction(){
                this.$store.dispatch('incCount')
            }
        },


        computed: {
            // count(){
            //     return this.$store.state.count
            // }
            ...mapState([ //映射 state 里面的数据
                'count'
            ]),
            //映射 getters里面的方法
            ...mapGetters([
                'reverseMsg'
            ]),
            //映射 actions 异步操作方法
            ...mapActions([
                'incCount'
            ])

        }
    }
</script>

<style scoped>

</style>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值