vuex的简单使用

1、vuex是干什么的?

学习任何东西,必然绕不过去的一个话题,就是我们为什么要使用它,它解决了什么问题?

vuex是基于vue框架的一个状态管理库。可以管理复杂应用的数据状态,比如兄弟组件的通信、多层嵌套的组件的传值等等。

vuex有这么几个核心概念——State、Getter、Mutation、Action、Module。

2、vuex的“hello world”示例

由于数据状态在多个组件维护的困难性,vuex在维护数据状态的时候,使用的方法就是对一个“容器”进行维护。这个容器是一个状态数,用对象的方式来表示。

(1)、store

const store = new Vuex.Store({
        state: {
            count: 0
        },
        mutations: {
            increment (state) {
                state.count++
            },
            decrement (state) {
                state.count--
            }
        }
    })

store是vuex的核心对象,它记录了整个vue应用的数据状态以及操作数据的方式。

(2)、state

state就是store操作的数据状态对象。

(3)、mutation

mutation提供了一种简单易用的同步的方式改变state的状态。

完整示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vuex学习</title>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
    <script src="https://unpkg.com/vuex"></script>
</head>
<body>
<div id="app">
    <p>{{ count }}</p>
    <p>
        <button @click="increment">+</button>
        <button @click="decrement">-</button>
    </p>
</div>
</body>
<script>
    const store = new Vuex.Store({
        state: {
            count: 0
        },
        mutations: {
            increment (state) {
                state.count++
            },
            decrement (state) {
                state.count--
            }
        }
    })

    new Vue({
        el:'#app',
        store,
        computed:{
            count(){
                return store.state.count;
            }
        },
        methods:{
            increment(){
                store.commit('increment')
            },
            decrement () {
                store.commit('decrement')
            }
        }
    })
</script>

</html>

3、State

是一个单一状态树,这个state中维护着整个应用的数据管理的核心对象。

(1)、通过计算属性获取state

computed计算属性是获取vuex状态的最简单的方式。(store.state.count)
state变化,计算属性会重新获取state中变化的值。

const Counter = {
    template:"<span>{{count}}</span>",
    computed:{
        count(){ 
            return store.state.count//核心在这里。
        }
    }
}
(2)、把store的实例注入到每个子组件中

我们的需求,很多情况下要在不同的组件中引用store,我们可以跟组件中直接注入,然后就能在不同的子组件中获取state。

var app = new Vue({
    el:'#app',
    store:store//这里就是注入store的地方
})
(3)、mapState——获取多个state数据

由于计算属性每次基本上只能获取一个state中的变化。如果获取多个,就要多个计算属性来解决。这样代码就显得冗余。mapState就是用来解决这个问题。

mutations: mapState({
    //这是箭头函数的方式
    count: state => state.count,
    //这是传字符串的方式
    count: 'count',
    //如果要使用this,只能携程函数的方式。
    countAdd(state){ 
        return this.add + state.count
    }
})
(4)、获取多个state的混合写法(计算属性+mapState)
mutations:{
    count(){
        return store.state.count
    },
    ...mapState({ 其他state })
}

4、Getter

如果说state通过计算属性获取的数据,我们要经过一定的操作(比如排序),那么在Getter中我们就可以提供这种操作。使得我们获取的state达到我们的需求。

它的本质就是对state进行过滤

const store = new Vuex.Store({
    state:{ 
        todoList:[{ 
            id: 1,
            text: 'do something1',
            isDo: true
        },{ 
            id: 2,
            text: 'do something2',
            isDo: false
        }]
    },
    getters:{ 
        doneTodos: funciton(state){ 
            return state.todoList.map(item=>item.isDo == true)
        }
    }
})
(1)、获取getter——store.getters

是getter对外暴露的数据读取方式
如: store.getters.doneTodos获取了过滤后的state

(2)、Getter 也可以接受其他 getter 作为第二个参数
getters: {
  // ...
  doneTodosCount: (state, getters) => {
    return getters.doneTodos.length
  }
}
store.getters.doneTodosCount // -> 1
(3)、mapGetters——获取多个getters的方式

使用方式和mapState差不多

5、Mutation

这是vuex提供的唯一更改store的属性。

(1)、定义一个带有Mutation的store
const store = new Vuex.Store({
    state:{
        count: 0
    },
    mutations:{
        increment(state){ 
            state.count++
        }
    }
})

触发方式:store.commit(‘increment’)

通过这样的方式,让state中的数据改变。

(2)、提交载荷

意思就是在commit的时候,传入额外的参数

store.commit('increment',{
    num: 10
})

也可以是这样:

store.commit({
    type: 'increment',
    num: 10
})
(3)、应该遵守的相应规则

第一、提前在你的 store 中初始化好所有所需属性。

第二、当需要在对象上添加新属性时,你应该:
Vue.set(obj, ‘newProp’, 123)
state.obj = { …state.obj, newProp: 123 }
//这两种方式都是把对象obj更新。

6、Action

这个属性的作用类似于Mutation,但是它提交的是mutation,而不是变更状态。并且action可以包含任何异步状态。

(1)、注册action
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  }
})

actions中的函数的参数是context,这个context有commit、getter、state等属性。

(2)、分发 Action

定义好了Action,就需要在JavaScript中触发这个Action。我们通过dispatch来触发。

store.dispatch('increment')
// 以载荷形式分发
store.dispatch('incrementAsync', {
  amount: 10
})

// 以对象形式分发
store.dispatch({
  type: 'incrementAsync',
  amount: 10
})
(3)、异步操作
actions: {
  incrementAsync ({ commit }) {
    setTimeout(() => {
      commit('increment')
    }, 1000)
  }
}
(4)、在组件中分发 Action
this.$store.dispatch('xxx') //分发 action

7、module模块组

随着项目越来越大,我们定义的状态会越来越多,这个时候,我们要对我们的状态进行模块划分。而module就是来干这样的事情的。
第一步、定义模块。

const moduleA = {
    state:{},
    getters:{
    },
    mutations:{},
    actions:{}
}

第二步、改变 Vuex.Stroe 的写法。

store = new Vuex.Store({
    modules:{ a: moduleA }
})

第三步、在页面中的使用方式

<div>{{$store.state.a.count}}</div>

如果想在页面中使用computed直接获取,可以这样写:

computed:{
    count(){
        return this.$store.state.a.count;
    }
}
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值