首頁  >  文章  >  web前端  >  vue支援ajax嗎

vue支援ajax嗎

WBOY
WBOY原創
2022-07-01 16:47:053031瀏覽

vue本身是不支援ajax請求的,但是可以利用“vue-resource”、axios等插件實現vue發送ajax請求;axios是一個基於Promise的HTTP請求客戶端,用於發送請求,“ vue-resource」是一個外掛程式用於提供使用XMLHttpRequest或JSONP進行Web請求和處理回應的服務。

vue支援ajax嗎

本教學操作環境:windows10系統、Vue3版、Dell G3電腦。

vue支援ajax嗎

vue本身不支援發送AJAX請求,需要使用vue-resource(vue1.0版本)、axios(vue2.0版本)等外掛實作

axios是基於Promise的HTTP請求客戶端,用來發送請求,也是vue2.0官方推薦的,同時不再對vue-resource進行更新和維護

vue -resource是Vue.js的插件提供了使用XMLHttpRequest或JSONP進行Web請求和處理回應的服務。 

當vue更新到2.0之後,作者就宣告不再對vue-resource更新,而是推薦的axios,在這裡大家了解一下vue-resource就可以。

vue使用axios發送AJAX請求:

首頁安裝並引入axios

npm install axios -S

或在網路上直接下載axios.min.js檔案透過script src的方式進行文件的引入

<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請求

#1、基本使用格式

格式1:axios([options]) #這種格式直接將所有資料寫在options裡

格式2:axios.get(url[,options])

2、傳參方式:

透過url傳參考

透過params選項傳參

程式碼片段:

<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請求 (push,delete的非get方式的請求都一樣)

格式:axios.post(url,data,[options]) 或 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全域守衛

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)
  })

【相關推薦:《vue. js教程》】

以上是vue支援ajax嗎的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn