better-byte-26469
08/08/2022, 9:04 AMeager-rainbow-87882
08/08/2022, 12:24 PMloading
state to the GrowthBook instance, with Vue.set
(to turn it reactive), just before the call to load the features: Vue.set($growthbook, 'loading', true)
◦ When the fetch
is completed (inside the then
), you can update the reactive state: Vue.set($growthbook, 'loading', false)
• As usual with Nuxt plugins, we also inject the GrowthBook instance to the Nuxt root to expose it everywhere automatically: inject('growthbook', Vue.observable($growthbook))
• This way, anywhere in your application you may need to check for features, you can use the injected $growthbook
and reactively update your templates based on the loading
state plus the desired feature:
<div v-if="!$growthbook.loading && $growthbook.isOn('some-feature')">
The feature is enabled!
</div>
• You can also leverage the reactivity to watch
the loading
state if you need to do anything in the script instead of the template of any component/page of your application:
watch: {
'$growthbook.loading'() {
if (this.$growthbook.isOn('dark-mode')) {
localStorage['color-mode'] = 'dark'
} else {
localStorage.removeItem('color-mode')
}
}
}
• Bonus tip: Another important part of dealing with GrowthBook is to keep its attributes updated regarding the current state of the application (specially when it comes to the user state), to allow complex conditions to enable/disable features. So remember to update attributes with setAttributes
when user logs in/out, or just watch some global user state, if you have it, then update attributes anytime it changes:
watch: {
// We have a global `currentUser` state shared in all our components/pages.
currentUser: {
deep: true,
handler(currentUser) {
this.$growthbook.setAttributes({
..this.$growthbook.getAttributes(),
uid: currentUser?.uid ?? null,
email: currentUser?.email ?? null,
authenticated: !!currentUser
// Anything else you want to use from your users as an attribute.
})
}
}
}
better-byte-26469
08/08/2022, 12:42 PMeager-rainbow-87882
08/08/2022, 12:58 PMbetter-byte-26469
08/08/2022, 1:33 PM