In a non-single-file component Vue app, we can we define a mixin object like so:
var myMixin = {
created () {
this.hello()
},
methods: {
hello () { console.log('hello from mixin!') }
}
}
Then, we can "attach" it to a component using Vue.extend():
const Foo = Vue.extend({
mixins: [myMixin],
template: '<div>foo</div>'
})
In this example, we only attached this mixin to Foo, so you will only see that console.log message when this component is called.
You can find this example in /chapter-5/vue/mixins/basic.html in this book's GitHub repository.
For Nuxt apps, we create and keep the mixin object in the /plugins/ directory, in a .js file. Let's demonstrate this:
- Create a mixin-basic.js file in the /plugins/ directory with a function that prints a message on the browser console when the Vue instance is created:
// plugins/mixin-basic.js
export default {
created ()...