The plugins directory contains JavaScript plugins that you want to run before instantiating the root Vue.js Application. This is the place to add Vue plugins and to inject functions or constants. Every time you need to use Vue.use(), you should create a file in plugins/ and add its path to plugins in nuxt.config.js.
plugins文件夹包含你想要在vue实例💰运行的JavaScript插件。这是添加插件和注入函数和常量的地方,每次你想要使用Vue.use(),你应该在plugins/里创建一个文件并且增加它的路径到nuxt.config.js的plugins。
External Packages
You may want to use external packages/modules in your application (one great example is axios) for making HTTP requests for both server and client.
你可能想要在你的应用中使用外部软件包/模块(一个很好的例子是axios)为了服务端和客户端创建HTTP请求
First, install it via npm or Yarn.
首先通过npm或者yarn安装它
//yarn
yarn add @nuxtjs/axios
//npm
npm install @nuxtjs/axios
You can configure for example the axios interceptors to react on possible errors from your API calls across the application. In this example we redirect the user to a custom error page called sorry when we get a 500 status error from our API.
你能为案例配置axios拦截器,以便对应用程序中API调用可能出现的错误做出反应。在案例中当我们从api获取500状态错误时候,我们重定向用户到名为sorry的自定义错误页面。
//plugins/axios.js
export default function ({ $axios, redirect }) {
$axios.onError(error => {
if (error.response.status === 500) {
redirect('/sorry')
}
})
}
Last but not least, add the module and the newly created plugin to the project configuration.
最后,将模块和新创建的插件添加到项目配置中。
//nuxt.config.js
module.exports = {
modules: ['@nuxtjs/axios'],
plugins: ['~/plugins/axios.js']
}
Then we can use it directly in your page components:
然后你能在你的页面组件直接使用它
//pages/index.vue
<template>
<h1>{{ post.title }}</h1>
</template>
<script>
export default {
async asyncData ({ $axios, params }) {
const post = await $axios.$get(`https://api.nuxtjs.dev/posts/${params.id}`)
return { post }
}
}
</script>
Another way to use axios without installing the module is by importing axios direct in the