Home  >  Article  >  Web Front-end  >  Does vue support ajax?

Does vue support ajax?

WBOY
WBOYOriginal
2022-07-01 16:47:053037browse

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 src="js/axios.min.js"></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 class="lgD">
    <input type="text" placeholder="输入用户名"   v-model="loginForm.loginName"/>
</p>
<p class="lgD">
    <input type="password" placeholder="输入用户密码" v-model="loginForm.passWord"/>
</p>
<a class="register" @click="gotoRegister()">注册账号</a>
<p class="logC">
    <button @click="doLogin" type="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!

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