[英]How do I create a module to run some boilerplate code to keep my codebase DRY
I am doing this in all my vue modules 我正在所有vue模块中执行此操作
import axios from 'axios'
axios.defaults.xsrfHeaderName = 'X-CSRFTOKEN'
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.withCredentials = true
I would like to not repeat this and preferably do something like 我不想重复,最好做些类似的事情
import axios from './myaxios'
I tried: 我试过了:
import axios from 'axios'
function myaxios () {
axios.defaults.xsrfHeaderName = 'X-CSRFTOKEN'
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.withCredentials = true
return axios
}
export default myaxios
Does not work. 不起作用。 What am I doing wrong? 我究竟做错了什么?
You also have to call the function. 您还必须调用该函数。 Or just do it outside the function. 或者只是在函数之外执行。
import axios from 'axios'
function myaxios() {
axios.defaults.xsrfHeaderName = 'X-CSRFTOKEN'
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.withCredentials = true
return axios
}
export default myaxios()
OR 要么
import axios from 'axios'
axios.defaults.xsrfHeaderName = 'X-CSRFTOKEN'
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.withCredentials = true
export default axios
When you're doing that, you're simply exporting the function myaxios()
without actually invoking/calling it. 在执行此操作时,您仅导出函数myaxios()
而不实际调用/调用它。 You simply have to do it once, and probably in your main app.js
file (or the first entry point of your app): 您只需执行一次,并且可能在主app.js
文件(或应用程序的第一个入口点)中:
In the module, you can export the function as you have done. 在模块中,您可以按完成的方式导出功能。 In your entry file, simply import the module: 在您的条目文件中,只需导入模块:
// Import module
import myaxios from '/path/to/myaxious/module';
And then you have to invoke it so that the global settings will be set properly: 然后,您必须调用它,以便正确设置全局设置:
// Invoke module's default exported function
myaxios();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.