nuxt.js是基于vue的服务器端渲染框架,它使得基于vue的SPA应用变得非常简单。axios是当下最热门的ajax前后端数据交互库。那么如何在nuxt.js中使用axios?
安装axios
npm install @nuxtjs/axios
配置axios
nuxt.config.js
module.exports = {
modules: [
'@nuxtjs/axios',
],
}
使用axios
组件中
<template>
<div class="index">
{{ articleList }}
</div>
</template>
<script>
export default {
async asyncData({ app }){
//获取文章列表数据
let article = await app.$axios.get(`http://localhost:3000/article/list`)
return {articleList: article.data.data}
}
methods: {
async fetchSomething() {
const res = await this.$axios.get('http://localhost:3000/article/list')
this.data = res
}
}
}
</script>
Store中
async nuxtServerInit ({ commit }, { $axios }) {
const ip = await $axios.$get('http://icanhazip.com')
commit('SET_IP', ip)
}
{
actions: {
async getIP ({ commit }) {
const ip = await this.$axios.$get('http://icanhazip.com')
commit('SET_IP', ip)
}
}
}