search
HomeWeb Front-endFront-end Q&ADoes vue support ajax?

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.

Does vue support ajax?

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: &#39;&#39;,
          passWord: &#39;&#39;
        }
      }
    },
    methods: {
      gotoRegister:function(){
        this.$router.push({
          name:&#39;register&#39;
        });
      },
      doLogin(){
//接口  this.$axios.get(接口地址).then(function(respon){}).catch(function(error){})
        let _this = this;
        if (this.loginForm.loginName === &#39;&#39; || this.loginForm.passWord === &#39;&#39;) {
          alert(&#39;账号或密码不能为空&#39;);
        } else {
          this.$axios.get("/WebUserLogin",{
            params:_this.loginForm
          }).then(res=>{
            var result = JSON.parse(res.data);
            // console.log(result);
            if (result.state == &#39;ok&#39;) {
               // console.log(&#39;登陆成功&#39;);
               window.sessionStorage.setItem(&#39;token&#39;, result.token) //存入token
               _this.$router.push(&#39;/index&#39;);
            }else{
              alert(&#39;登录失败请检查用户名和密码是否正确&#39;);
            }
          }).catch(error => {
            alert(&#39;账号或密码错误&#39;);
            // 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 &#39;qs&#39;
  export default {
    data:function(){
      return{
        none: false,
        registerForm: {
          LoginName: &#39;&#39;,
          LoginPassword: &#39;&#39;
        }
      }
    },
    methods: {
        register(){
          let _this = this;
          if (this.registerForm.LoginName === &#39;&#39; || this.registerForm.LoginPassword === &#39;&#39;) {
            alert(&#39;注册信息不能空&#39;);
          } 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 == &#39;ok&#39;) {
                 alert(&#39;注册成功去登录&#39;);
                 _this.$router.push(&#39;/&#39;);
              }else{
                alert(&#39;注册失败请检查注册信息是否正确&#39;);
              }
            }).catch(error => {
              alert(&#39;注册信息有误&#39;);
              // 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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to Use useState() Hook in Functional React ComponentsHow to Use useState() Hook in Functional React ComponentsApr 30, 2025 am 12:25 AM

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-Focused Nature: Managing Complex Application StateReact's View-Focused Nature: Managing Complex Application StateApr 30, 2025 am 12:25 AM

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.

Integrating React with Other Libraries and FrameworksIntegrating React with Other Libraries and FrameworksApr 30, 2025 am 12:24 AM

IntegratingReactwithotherlibrariesandframeworkscanenhanceapplicationcapabilitiesbyleveragingdifferenttools'strengths.BenefitsincludestreamlinedstatemanagementwithReduxandrobustbackendintegrationwithDjango,butchallengesinvolveincreasedcomplexity,perfo

Accessibility Considerations with React: Building Inclusive UIsAccessibility Considerations with React: Building Inclusive UIsApr 30, 2025 am 12:21 AM

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

SEO Challenges with React: Addressing Client-Side Rendering IssuesSEO Challenges with React: Addressing Client-Side Rendering IssuesApr 30, 2025 am 12:19 AM

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.

The Benefits of React's Strong Community and EcosystemThe Benefits of React's Strong Community and EcosystemApr 29, 2025 am 12:46 AM

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

React Native for Mobile Development: Building Cross-Platform AppsReact Native for Mobile Development: Building Cross-Platform AppsApr 29, 2025 am 12:43 AM

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

Updating State Correctly with useState() in ReactUpdating State Correctly with useState() in ReactApr 29, 2025 am 12:42 AM

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.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools