풀스택 개발 공부로그

Vue.js, Nuxt.js Plugins

|

vuejs plugins

Vue.js

Introduction

https://vuejs.org/v2/guide/plugins.html

Plugins usually add global-level functionality to Vue. There is no strictly defined scope for a plugin - there are typically several types of plugins:

plugins는 전역적인 수준에서 기능되록 뷰에 등록됩니다.

install and use

Use plugins by calling the Vue.use() global method. This has to be done before you start your app by calling new Vue():

// calls `MyPlugin.install(Vue)`
Vue.use(MyPlugin)

new Vue({
  //… options
})

You can optionally pass in some options:

Vue.use(MyPlugin, { someOption: true })

Nuxt js

Setup - Axios Module

install (nuxt.config.js)

// nuxt.config.js
module.exports = {
  modules: [
    @nuxtjs/axios’,
  ],

  axios: {
    // proxyHeaders: false
  }
}

Usage

asyncData

async asyncData({ $axios }) {
  const ip = await $axios.$get(http://icanhazip.com’)
  return { ip }
}

methods/created/mounted/etc

methods: {
	async fetchSomething() {
	const ip = await this.$axios.$get('http://icanhazip.com')
	this.ip = ip
	}
}

Extending axios

If you need to customize axios by registering interceptors and changing global config, you have to create a nuxt plugin.

커스터마이징이 필요하면 nuxt plugins를 사용

// nuxt.config.js
{
	modules: [
		'@nuxtjs/axios',
	],

	plugins: [
		'~/plugins/axios'
	]
}
//plugins/axios.js
export default function ({ $axios, redirect }) {
	$axios.onRequest(config => {
	console.log('Making request to ' + config.url)
})

$axios.onError(error => {
	const code = parseInt(error.response && error.response.status)
		if (code === 400) {
			redirect('/400')
		}
	})
}

참고 : Helpers - Axios Module

fetch style requests

Helpers - Axios Module

Axios plugin also supports fetch style requests with $ prefixed methods:

// Normal usage with axios
let data = (await $axios.get('...')).data

// Fetch Style
let data = await $axios.$get('...')
set headers

Helpers - Axios Module

set token

Helpers - Axios Module