How to use Mixins in Nuxt.JS with Example

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

Mixins are common features for all frameworks. 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 with an example.

How to use Mixin in Nuxt.JS with Example

Mixins in Nuxt.JS
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. You can make all kinds of mixins functions like created , mounted hook or computed or data property. In this tutorial, I will show a method for our testing.

Let’s see a Mixin example on Vue. You have to create a js file for your functions.

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 : How to do Vue 3 Composition API CRUD with Tailwindcss

Now I will show you how you use re-use in Nuxt.JS. Well, Let’s create a file in the plugins folder, then write your code whatever you want. You can make an uncountable function as your wish.

Create a js file for your fucntions

plugins/mixins.js

import Vue from 'vue'

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

Vue.mixin(mixin)

Well, our function has been done. Though it is a silly function, I have created it for this tutorial. Now you have to register this file in the nuxt,config.js file.

Add plugins name

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

Inside the plugins array, you have to register all files which are you create in the plugin folder.

Well, Our setup has been done. Now you can use this function in all components whatever you want. It will merge with all methods.

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

Hope It will help you. I hope you are enjoying this tutorial. Good Luck! Enjoy your Code.


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 *