Let's say I created a plugin in my Nuxt app:
plugins: [
'~/plugins/toggler',
],
which contains:
import Vue from 'vue'
Vue.mixin({
data() {
return {
isActive: false
}
},
methods: {
toggler() {
this.isActive = !this.isActive
},
},
})
I would like to toggle classes on elements on different components, like:
<div :class="{ 'is-active': isActive }"></div>
and it's correctly triggered via a button:
<button @click.prevent="toggler" />
However, this only change the class on other elements inside the same .vue component where the button is.
Other elements with the same :class="{ 'is-active': isActive }" in different .vue components aren't affected, unless I add a button in those components too.
Here's a sandbox: https://codesandbox.io/s/tender-http-fqlx5
Why you create a mixin in a plugin?
Create and usage mixin:
create:
In the mixins folder inside You're creating a mixin file (example.js)
usage:
import into the component:
import example from '~/mixins/example'
Mixin definition into component into script:
export default {
mixins: [example],
data() {
return {}
},
computed: {},
methods: {}
}
This allows it to be reused into any component.