Skip to content

Commit b40ee5d

Browse files
docs: add a description of providing store to Vue instance (#1468)
1 parent 481dbf9 commit b40ee5d

File tree

1 file changed

+35
-1
lines changed

1 file changed

+35
-1
lines changed

docs/guide/README.md

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,10 @@ At the center of every Vuex application is the **store**. A "store" is basically
1515
After [installing](../installation.md) Vuex, let's create a store. It is pretty straightforward - just provide an initial state object, and some mutations:
1616

1717
``` js
18-
// Make sure to call Vue.use(Vuex) first if using a module system
18+
import Vue from 'vue'
19+
import Vuex from 'vuex'
20+
21+
Vue.use(Vuex)
1922

2023
const store = new Vuex.Store({
2124
state: {
@@ -37,6 +40,37 @@ store.commit('increment')
3740
console.log(store.state.count) // -> 1
3841
```
3942

43+
In order to have an access to `this.$store` property in your Vue components, you need to provide the created store to Vue instance. Vuex has a mechanism to "inject" the store into all child components from the root component with the `store` option:
44+
45+
``` js
46+
new Vue({
47+
el: '#app',
48+
store: store,
49+
})
50+
```
51+
52+
:::tip
53+
If you're using ES6, you can also go for ES6 object property shorthand notation (it's used when object key has the same name as the variable passed-in as a property):
54+
55+
```js
56+
new Vue({
57+
el: '#app',
58+
store
59+
})
60+
```
61+
:::
62+
63+
Now we can commit a mutation from component's method:
64+
65+
``` js
66+
methods: {
67+
increment() {
68+
this.$store.commit('increment')
69+
console.log(this.$store.state.count)
70+
}
71+
}
72+
```
73+
4074
Again, the reason we are committing a mutation instead of changing `store.state.count` directly, is because we want to explicitly track it. This simple convention makes your intention more explicit, so that you can reason about state changes in your app better when reading the code. In addition, this gives us the opportunity to implement tools that can log every mutation, take state snapshots, or even perform time travel debugging.
4175

4276
Using store state in a component simply involves returning the state within a computed property, because the store state is reactive. Triggering changes simply means committing mutations in component methods.

0 commit comments

Comments
 (0)