vue

vuex的安装和使用

2019-05-16  本文已影响0人  夕禾口

安装并使用vuex

    new vue({
    //state
    data(){
        return {
            count:0
        }
    },
    //view
    template:'<p>{{count}}</p>',
    
    //actions
    methods:{
        increment(){
            this.count++
        }
    }
})
    const store = new Vuex.Store({
        state:{
            count:0
        },
        
        mutations:{
            state.count++
        }
    })

现在可以通过store.state 来获取状态对象,以及通过state.commit 方法触发状态变更

    store.commit('increment')
    console.log(store.state.count)
    // -> 1

每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。Vuex 和单纯的全局对象有以下两点不同:

  • Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
  • 你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。

ps:想吐槽一下,vue和vuex的官方文档,看的我头大~~~

上一篇下一篇

猜你喜欢

热点阅读