Vue itself does not support ajax requests, but you can use "vue-resource", axios and other plug-ins to implement vue to send ajax requests; axios is a Promise-based HTTP request client used to send requests, " vue-resource" is a plug-in that provides services for making web requests and processing responses using XMLHttpRequest or JSONP.
The operating environment of this tutorial: Windows 10 system, Vue3 version, Dell G3 computer.
Does vue support ajax?
Vue itself does not support sending AJAX requests. You need to use vue-resource (vue1.0 version), axios (vue2.0 version) and other plug-ins to implement
axios is a Promise-based HTTP request client, used to send requests, and is also officially recommended by vue2.0. At the same time, vue-resource will no longer be updated and maintained
vue -resource is a plug-in for Vue.js that provides services for making web requests and processing responses using XMLHttpRequest or JSONP.
When vue is updated to 2.0, the author announced that he will no longer update vue-resource, but recommends axios. Here you can learn about vue-resource.
vue uses axios to send AJAX requests:
Install and introduce axios on the homepage
npm install axios -S
Or directly download the axios.min.js file online through script src File introduction
<script></script>
import axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios,axios); Vue.prototype.$axios = axios;
*get request
1. Basic usage format
Format 1: axios([options]) #This This format directly writes all data in options
Format 2: axios.get(url[,options])
2. Parameter passing method:
Pass through url Parameters
Pass parameters through params option
Code snippet:
<p> <input> </p> <p> <input> </p> <a>注册账号</a> <p> <button>立即登录</button> </p>
<script> export default { data:function(){ return{ none: false, loginForm: { loginName: '', passWord: '' } } }, methods: { gotoRegister:function(){ this.$router.push({ name:'register' }); }, doLogin(){ //接口 this.$axios.get(接口地址).then(function(respon){}).catch(function(error){}) let _this = this; if (this.loginForm.loginName === '' || this.loginForm.passWord === '') { alert('账号或密码不能为空'); } else { this.$axios.get("/WebUserLogin",{ params:_this.loginForm }).then(res=>{ var result = JSON.parse(res.data); // console.log(result); if (result.state == 'ok') { // console.log('登陆成功'); window.sessionStorage.setItem('token', result.token) //存入token _this.$router.push('/index'); }else{ alert('登录失败请检查用户名和密码是否正确'); } }).catch(error => { alert('账号或密码错误'); // console.log(error); }); } } } } </script>
*post request (the non-get requests of push and delete are the same)
Format: axios.post(url,data,[options]) or axios([options])
<script> import qs from 'qs' export default { data:function(){ return{ none: false, registerForm: { LoginName: '', LoginPassword: '' } } }, methods: { register(){ let _this = this; if (this.registerForm.LoginName === '' || this.registerForm.LoginPassword === '') { alert('注册信息不能空'); } else { this.$axios({ url:"/WebUserRegist", method:"post", data:qs.stringify(_this.registerForm) }).then(res=>{ var result = JSON.parse(res.data); // console.log(result); if (result.state == 'ok') { alert('注册成功去登录'); _this.$router.push('/'); }else{ alert('注册失败请检查注册信息是否正确'); } }).catch(error => { alert('注册信息有误'); // console.log(error); }); } } } } </script>
index.js global guard
router.beforeEach((to,form,next) =>{ //如果进入到的路由是登录页或者注册页面,则正常展示 if (to.path === '/login') { next(); } else { let token = window.sessionStorage.getItem('token'); // console.log(token) if (token === null || token === '') { next('/login'); // alert("还没有登录,请先登录!"); } else { next(); } } // console.log(to) })
[Related recommendations: "vue. js tutorial》】
The above is the detailed content of Does vue support ajax?. For more information, please follow other related articles on the PHP Chinese website!

useState allows state to be added in function components because it removes obstacles between class components and function components, making the latter equally powerful. The steps to using useState include: 1) importing the useState hook, 2) initializing the state, 3) using the state and updating the function.

React's view focus manages complex application state by introducing additional tools and patterns. 1) React itself does not handle state management, and focuses on mapping states to views. 2) Complex applications need to use Redux, MobX, or ContextAPI to decouple states, making management more structured and predictable.

IntegratingReactwithotherlibrariesandframeworkscanenhanceapplicationcapabilitiesbyleveragingdifferenttools'strengths.BenefitsincludestreamlinedstatemanagementwithReduxandrobustbackendintegrationwithDjango,butchallengesinvolveincreasedcomplexity,perfo

TomakeReactapplicationsmoreaccessible,followthesesteps:1)UsesemanticHTMLelementsinJSXforbetternavigationandSEO.2)Implementfocusmanagementforkeyboardusers,especiallyinmodals.3)UtilizeReacthookslikeuseEffecttomanagedynamiccontentchangesandARIAliveregio

SEO for React applications can be solved by the following methods: 1. Implement server-side rendering (SSR), such as using Next.js; 2. Use dynamic rendering, such as pre-rendering pages through Prerender.io or Puppeteer; 3. Optimize application performance and use Lighthouse for performance auditing.

React'sstrongcommunityandecosystemoffernumerousbenefits:1)ImmediateaccesstosolutionsthroughplatformslikeStackOverflowandGitHub;2)Awealthoflibrariesandtools,suchasUIcomponentlibrarieslikeChakraUI,thatenhancedevelopmentefficiency;3)Diversestatemanageme

ReactNativeischosenformobiledevelopmentbecauseitallowsdeveloperstowritecodeonceanddeployitonmultipleplatforms,reducingdevelopmenttimeandcosts.Itoffersnear-nativeperformance,athrivingcommunity,andleveragesexistingwebdevelopmentskills.KeytomasteringRea

Correct update of useState() state in React requires understanding the details of state management. 1) Use functional updates to handle asynchronous updates. 2) Create a new state object or array to avoid directly modifying the state. 3) Use a single state object to manage complex forms. 4) Use anti-shake technology to optimize performance. These methods can help developers avoid common problems and write more robust React applications.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6
Visual web development tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

WebStorm Mac version
Useful JavaScript development tools
