I want to create custom object that could be available globally in every place (plugins, middleware, component’s created/computed/mounted methods)
I could access global object with context property (custom plugin, custom router middleware … ),
but how to access it in component’s created()
?
Advertisement
Answer
You can use the store to for global variables:
📄 https://nuxtjs.org/guide/vuex-store
1/ Create store:
JavaScript
x
18
18
1
// your-project/store/index.js
2
3
export const state = () => ({
4
var1: null,
5
var2: null
6
})
7
8
export const mutations = {
9
SET_VAR_1 (state, value) {
10
console.log('SET_VAR_1', value)
11
state.var1 = value
12
},
13
SET_VAR_2 (state, value) {
14
console.log('SET_VAR_2', value)
15
state.var2 = value
16
}
17
}
18
2/ Read data store
Then you can get or set var1
& var2
, from any <page>.vue
or <layout>.vue
or <plugin>.vue
or <middleware>.vue
.
From <template>
with $store
:
JavaScript
1
10
10
1
// your-project/pages/index.js
2
3
<template>
4
<section>
5
<h2>From Store</h2>
6
<div>var1 = {{ $store.state.var1 }}</div>
7
<div>var2 = {{ $store.state.var2 }}</div>
8
</section>
9
</template>
10
or from <script>
with injection on asyncData
:
JavaScript
1
21
21
1
// your-project/pages/index.js
2
3
<template>
4
<section>
5
<h2>From Store</h2>
6
<div>var1 = {{ var1 }}</div>
7
<div>var2 = {{ var2 }}</div>
8
</section>
9
</template>
10
11
<script>
12
export default {
13
async asyncData ({ store }) {
14
return {
15
var1: store.state.var1,
16
var2: store.state.var2
17
}
18
}
19
}
20
</script>
21
3/ Update data store
JavaScript
1
10
10
1
<script>
2
export default {
3
async asyncData ({ store }) {
4
5
store.commit('SET_VAR_1', 'foo')
6
store.commit('SET_VAR_2', 'bar')
7
}
8
}
9
</script>
10
4/ Component & Store
From <component>.vue
you have not to directly fetch the Store.
So you have to pass data from nuxt file to component file with a custom attribute:
JavaScript
1
8
1
// your-project/pages/example.js
2
3
<template>
4
<section>
5
<my-component :var1="$store.state.var1" :var2="$store.state.var2" />
6
</section>
7
</template>
8
then
JavaScript
1
15
15
1
// your-project/components/MyComponent.js
2
<template>
3
<section>
4
<h2>From props</h2>
5
<div>var1 = {{ var1 }}</div>
6
<div>var2 = {{ var2 }}</div>
7
</section>
8
</template>
9
10
<script>
11
export default {
12
props: ['var1', 'var2']
13
}
14
</script>
15