How to use Mixins in Nuxt.JS with Example

Mixins in Nuxt.JS
Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Hello Developers,

How are you doing? In this tutorial, I will show you how to use mixins in Nuxt.JS. If you don’t know What is the mixins in Vue.JS, don’t worry I will discuss with you everything in detail step by step by example.

Mixins in Nuxt.JS
Mixins in Nuxt.JS

So what is Mixins in Vue JS?

Well, Mixins are a flexible way to distribute reusable functionalities for Vue components. A mixin object can contain any component options. When a component uses a mixin, all options in the mixin will be “mixed” into the component’s own options.

Let’s see an Mixin example on Vue. You can create a js file for your mixins.

mixins.js

// define a mixin object
const myMixin = {
  methods: {
    shortMyText (text, n) {
      return text.substr(0, n)
    }
  }
}

// define a component that uses this mixin
const Component = Vue.extend({
  mixins: [myMixin]
})

Read More : The magic of Laravel Macro and Mixins with Examples

Now I will show you how you use mixins in Nuxt.JS . Well,Let’s create a file in plugins folder,then write your code whatever you want.

plugins/mixins.js

import Vue from 'vue'

const mixin = {
   methods: {
    shortMyText (text, n) {
      return text.substr(0, n)
    }
  }
}

Vue.mixin(mixin)

Now you have to register this file in nuxt,config.js file.

  plugins: [
    '~/plugins/mixins',
  ],

inside the plugins array you have to register all file which is you create in plugin folder.

Well,Our set up has done. Now you can use this function in all components whatever you want.

<script>
export default {
created(){
this.shortMyText('shahin',2)
  }
}
</script>
output : //sh

Hope It will help you.


Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  

About Anisur Rahman Shahin

Hello. My name is Shahin. I'm a tech enthusiast guy. Personally, I’m Optimistic and always in hurry kinda person. I'm a freelance web developer. I am working at Zakir Soft as Laravel Developer. My Portfolio website: https://devshahin.com/

View all posts by Anisur Rahman Shahin →

One Comment on “How to use Mixins in Nuxt.JS with Example”

Leave a Reply

Your email address will not be published. Required fields are marked *