vuex的学习

287 阅读2分钟

一,在组件外面访问vuex

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</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@3.0.1/dist/vuex.js"></script>
</head>
<body>
    <div id="app">
        <h1>Hello Vuex! 我来啦</h1>
    </div>

    <script>

      const store = new Vuex.Store({
        state: {
          count: 0
        },
        mutations: {
          increment (state) {
            state.count++
          },
        },
        actions: {
          getIncrement(context) {
            context.commit('increment')
          }
        },
        getters: {
          count: state => state.count
        }
      })
      console.log(store)
    </script>
</body>
</html>

console.log(store)输出的是下面的这些!!


所以输出结果显示store是一个对象,我们有很多方法可以调用。

如果我们想执行actions的 getIncrement方法,我们就store.dispatch('getIncrement')

  • 我们可以看到dispatch接收两个参数(type,payload)也就是说我们dispatch一个actions的方法我们可以传参进去。
  • 想获取count,我们可以store.state.count 如果我们对state进行映射一个getters就可以直接访问store.getters.count

二、如果我们想在组件里访问vuex的actions的方法,state的保存的值,该怎么做的?

const store = new Vuex.Store({...})

我们可以把store注入到vue实例里。

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</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@3.0.1/dist/vuex.js"></script>
</head>
<body>
<div id="app">
    <h1>Hello Vuex! 我来啦</h1>
    <p>{{$store.state.count}}</p>
</div>

<script>

  const store = new Vuex.Store({
    state: {
      count: 0
    },
    mutations: {
      increment(state) {
        state.count++
      },
    },
    actions: {
      getIncrement(context) {
        context.commit('increment')
      }
    },
    getters: {
      count: state => state.count
    }
  })

  var vm = new Vue({
    el: "#app",
    store
  })
  console.log(vm)
</script>
</body>
</html>

我们把store注入到vue实例里面,我们console.log(vm)输出的是:


这时候vm也就说vue的实例里面就有$store,在组件里我们就可以$store.dispatch一个actions的方法,也可以$store.state.count 访问state的值。


以上例子演示如何在组件外面和组件里面访问vuex的state和actions和mutations


  • 后面会分享 mapActions ,mapGetters ,mapMutations,createNamespacedHelpers使用方法