Hooke

在 vue 组件中获得 vuex 状态

1 +/node_modules
1 +const store = new Vuex.Store({
2 + state: {
3 + count: 0
4 + },
5 + mutations: {
6 + increment: state => state.count++,
7 + decrement: state => state.count--
8 + }
9 +})
10 +
11 +const Counter = {
12 + template: `<div>{{ count }}</div>`,
13 + computed: {
14 + count () {
15 + return this.$store.state.count
16 + }
17 + }
18 +}
19 +
20 +Vue.component('counter',Counter)
21 +
22 +const app = new Vue({
23 + el: '#app',
24 + store,
25 + computed: {
26 + count() {
27 + return store.state.count
28 + }
29 + },
30 + methods: {
31 + increment() {
32 + store.commit('increment')
33 + },
34 + decrement() {
35 + store.commit('decrement')
36 + }
37 + }
38 +})
1 +<!DOCTYPE html>
2 +<html>
3 + <head>
4 + <meta charset="utf-8">
5 + <title>vuex</title>
6 +
7 +
8 + </head>
9 + <body>
10 + <div id="app">
11 + <counter></counter>
12 + <p>
13 + <button @click="increment">+</button>
14 + <button @click="decrement">-</button>
15 + </p>
16 + </div>
17 + <script src="./node_modules/vue/dist/vue.js" charset="utf-8"></script>
18 + <script src="./node_modules/vuex/dist/vuex.js" charset="utf-8"></script>
19 + <script src="./app.js" charset="utf-8"></script>
20 + </body>
21 +</html>
1 +{
2 + "name": "demo-vue-vuex",
3 + "version": "1.0.0",
4 + "description": "",
5 + "main": "index.js",
6 + "scripts": {
7 + "test": "echo \"Error: no test specified\" && exit 1"
8 + },
9 + "repository": {
10 + "type": "git",
11 + "url": "git@gitlab.kmlab.com:hooke1234/demo-vue-vuex.git"
12 + },
13 + "author": "",
14 + "license": "ISC",
15 + "dependencies": {
16 + "vue": "^2.0.3",
17 + "vuex": "^2.0.0"
18 + }
19 +}