vuejs calls the method in the js file: 1. Create a new js file under the assets file; 2. Use "export default {...}" to reference it in the component that needs to use the method.
The operating environment of this article: Windows7 system, Vue2.9.6 version, DELL G3 computer
How does vuejs call the method in the js file ?
How to reference js files in vue
In many components of vue, axios is used to post data, and each component is written with a The post method is also possible, just copy it, but it always feels a bit inconvenient. Wouldn't it be better to write the axios post into a separate js file and then reference it in the required components?
1. Create a new js file under the assets file
Create a new file named webpost.js
import axios from 'axios' //Post方法的封装 function axiosPost(url,params){ return new Promise((resolve, reject) => { axios({ url: url, method: 'post', data: params, headers: { 'Content-Type':'application/json' } }) .then(res=>{ resolve(res.data); }); }); } export { axiosPost }
This needs to specifically quote axios, which is the first line. Then you can use it. The last sentence is very important, otherwise you will not be able to call
in other components. 2. Reference
<script> import {axiosPost} from '../assets/webpost'; export default { }
in the component that needs to use this method. Pay attention to the path of the reference. The content in import {} is the content in the export above.
When using it, you don’t even need this, just axiosPost.
axiosPost(url,params) .then(res=>{ if (res===401){ this.$message.error('哦,对不起,你所输入的用户名或密码有误!'); }else{ }
3. Another way to write js
The following is the re-edited part. In the past few days, I have sorted out the axios part and added an interceptor to bring token verification when requesting the api. There is only one more export, and you can write multiple. The structure is clearer and easier to understand.
import axios from 'axios' //Post方法的封装 export function axiosPost(url,params){ return new Promise((resolve, reject) => { //以下部分是拦截器功能 axios.interceptors.request.use(config=>{ const token=localStorage.getItem('token') if(token){ config.headers.authorization=token } return config },err=>{ }) //下面是正常的 axios({ url: url, method: 'post', data: params, headers: { 'Content-Type':'application/json' } }) .then(res=>{ resolve(res.data); }); }); }
Recommended: "The latest 5 vue.js video tutorial selections"
The above is the detailed content of How to call methods in js files in vuejs. For more information, please follow other related articles on the PHP Chinese website!