This is the third day of my participation in the August More text Challenge. For details, see:August is more challenging

Follow the article “build SSR mall with NuxtJS actual notes — AXIOS configuration and cross-domain implementation” to continue our journey of moving bricks. There are deficiencies or any suggestions, welcome you to do not hesitate to make corrections. This paper mainly introduces the unified management of API module in VUE back-end rendering (SSR) project based on NuxtJS

Creating an API module

In the project, if the request interface to write the request where, one is to add repetitive code, two is not easy to manage and maintenance, so generally write the API together for centralized management. Since nuxt’s directory structure is defined, we create an API directory under assets and create index.js under that directory as the API module entry file, export modules object, and key to each file name in the modules directory. Value is the corresponding function:

// assets\api\index.js
// require.context is a webpack method
const modulesFiles = require.context('./modules'.true./\.js$/)
const modules = modulesFiles.keys().reduce((modules, modulePath) = > {
  // Replace a pathname such as./passport. Js with passport
  const moduleName = modulePath.replace(/^\.\/(.*)\.js$/.'$1')
  // Import the module
  const value = modulesFiles(modulePath)
  // Default is the property of value, which defines the value exposed in the JS file in modules
  modules[moduleName] = value.default || value
  return modules
}, {})

export default modules // Export modules object, key is each file name in the modules directory, value is the corresponding function
Copy the code

Description:

  • require.contextThe webpack method allows you to create your own context, which is usually used to batch import modules.
    1. The first parameter./modules: indicates the path of the file to be searched
    2. Second parametertrue: means to find a subdirectory,falseDo not search for subdirectories
    3. The third argument is a re: specifies the filename format of the file to match, in this case finding all JS files
  • keys:require.context()The value is an array of the names of successfully matched modules, such as the directory structure of



Gets themodulesFiles.keys()The values of:

['./passport.js'.'./setting.js' ]
Copy the code
  • const value = modulesFiles(modulePath), print outvalue, the following results can be obtained, as can be seenvalue.defaultIs the exported value of the file (setting.js) to be defined in the modules directory.axios => ({})) :
Object [Module] { default: [Function]}Copy the code

Create a new directory in the API directory to store the different API files, such as setting.js:

// Axios is passed in plugins/api.js
export default axios => ({
  settingByDomain(domain) {
    return axios({
      url: `/api/web/setting/by-domain/${domain}`.method: 'get'})}})Copy the code

Inject the Vue instance, server-side context, and Vuex

Create API. Js in plugins directory and use inject to expose API. We want these apis to be available throughout the application, so we need to inject them into the Vue instance (client), context (server), and Store (Vuex). By convention, new attribute or method names are prefixed with $:

// plugins/api.js   
import apis from '@/assets/api/index'
// inject is used to inject API into context, Vue instance, Vuex
export default ({ $axios }, inject) => {
  const apiObject = {}
  for (const i in apis) {
    // Pass $axios to the functions that are exported by default by js files defined in API /modules
    apiObject[i] = apis[i]($axios)
  }

  // The system automatically adds $to the front of the method name API
  inject('api', apiObject)
}
Copy the code

The inject method is the second argument to the plugin export function. The system will automatically add $to the method name. So you call $API.

Configuration nuxt. Config. Js

All plugins configured by the plugins attribute are loaded and imported before the Nuxt.js application is initialized

plugins: ['@/plugins/api']  
Copy the code

use

Can be used in the actions or mutation methods of context, Vue instance, or Vuex:

context

There are some hooks that can be found directly by deconstructing the assignment, and are generally used on the server side:

// store/index.js 
export const actions = {
  async nuxtServerInit(store, { $api }) {
    try {
      const res = await $api.setting.settingByDomain(domain)
      // ...
    } catch (error) {
      console.log(error)
    }
  }
}
Copy the code

Vue instance

With this, the vue instance, you can directly get:

methods: { 
  handle() { 
    this.$api.test.appUser().then(res= > { console.log(res) }) 
  } 
}
Copy the code

In the Vuex

This is also the vuex instance store:

export const actions = { 
  login({ commit }, userInfo) { 
    return new Promise((resolve, reject) = > { 
      // ... 
      this.$api.passport.login(clientSetting)
        .then(res= > { console.log(res) })
        .catch(error= > { reject(error) }) 
    }) 
  } 
}
Copy the code

Note: Generally, functions in mutation are written as arrow functions, but if you want this to point to a VUex instance, you need to use a non-arrow function.