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()
?
It's also possible to inject an object. Useful if you want to create a plugin available everywhere.
Here nuxt doc about this combined-inject.
// nuxt.config.js
export default {
plugins: ['~/plugins/myPlugin.js']
}
// plugins/myPlugin.js
import Vue from 'vue'
export default ({ app }, inject) => {
inject('myPlugin', Vue.observable({ foo: 'bar' }))
}
And then you can access your plugin via prefix $
.
// components/MyComponent.vue
<template>
<div :class="$myPlugin.foo">
{{ $myPlugin.foo }}
</div>
</template>
<script>
export default {
methods: {
aMethod() {
return this.$myPlugin.foo
}
}
}
</script>
It's also available in vuex and nuxt server context.
You can inject objects or functions.
Here to learn more about client/server injection.
You can use the store to for global variables:
📄 https://nuxtjs.org/guide/vuex-store
// your-project/store/index.js
export const state = () => ({
var1: null,
var2: null
})
export const mutations = {
SET_VAR_1 (state, value) {
console.log('SET_VAR_1', value)
state.var1 = value
},
SET_VAR_2 (state, value) {
console.log('SET_VAR_2', value)
state.var2 = value
}
}
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
:
// your-project/pages/index.js
<template>
<section>
<h2>From Store</h2>
<div>var1 = {{ $store.state.var1 }}</div>
<div>var2 = {{ $store.state.var2 }}</div>
</section>
</template>
or from <script>
with injection on asyncData
:
// your-project/pages/index.js
<template>
<section>
<h2>From Store</h2>
<div>var1 = {{ var1 }}</div>
<div>var2 = {{ var2 }}</div>
</section>
</template>
<script>
export default {
async asyncData ({ store }) {
return {
var1: store.state.var1,
var2: store.state.var2
}
}
}
</script>
<script>
export default {
async asyncData ({ store }) {
store.commit('SET_VAR_1', 'foo')
store.commit('SET_VAR_2', 'bar')
}
}
</script>
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:
// your-project/pages/example.js
<template>
<section>
<my-component :var1="$store.state.var1" :var2="$store.state.var2" />
</section>
</template>
then
// your-project/components/MyComponent.js
<template>
<section>
<h2>From props</h2>
<div>var1 = {{ var1 }}</div>
<div>var2 = {{ var2 }}</div>
</section>
</template>
<script>
export default {
props: ['var1', 'var2']
}
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With