vue-cli安装及axios基础使用

Vue-cli安装及axios基础使用

 

vue-cli是一个很方便的脚手架,安装过程可按菜鸟教程

地址:http://www.runoob.com/vue2/vue-install.html

全程按着菜鸟教程走就可以了,没有npm或者cnpm(淘宝镜像)请去node官网下载安装Node(Node自带),剩下的看相关教程

 

 

 


安装完后,进入相应文件夹安装axios相关依赖

(--save和-dev没连在一起会有些小问题)

npm install axios --save-dev

 

在main.js中(全局)写入

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import axios from 'axios'

//axios.defaults.withCredentials=true   //全局请求头,这是比较常用的携带cookie
// axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest' //另一个例子
Vue.prototype.$axios = axios
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

若是只需要局部引入的话可以在相应文件中直接引入就好了

 

axios使用的两种方法(格式):

方法一:

<script>
export default {
      data(){
          return{
              info:[]
          }
      },
      methods:{

      },
      mounted(){
           //get或者post , api为接口地址
           this.$axios.get('api',{
                 params:{  //post不需要params:这部分
                       //请求参数
                 }
           }).then(res => {  //res是返回结果
               //你的下一步操作 例:
                this.info = res.data  //存数据
           }).catch(err => { //请求失败就会捕获报错信息
                 //err.response可拿到服务器返回的报错数据       
           })
      } 
}
</script>

方法二:

<script>
export default {
      data(){
          return{
              info:[]
          }
      },
      methods:{

      },
      mounted(){
           //get或者post , api为接口地址
           this.$axios({
               method:'post',
               url:'api',
               data:{  //get这里应为params
                  //请求参数
               },
               //withCredentials:true, //局部携带cookie
               headers:{} //如果需要添加请求头可在这写
           }).then(res => {  //res是返回结果
               //你的下一步操作 例:
                this.info = res.data  //存数据
           }).catch(err => { //请求失败就会捕获报错信息
                 //err.response可拿到服务器返回的报错数据       
           })
      } 
}
</script>

以上是axios使用方法,安装教程来自菜鸟

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值