axios请求HTTP和vuex数据管理 / 网络研习社#19

in #cn5 years ago

axios有点类似ajax,主要是发送请求,获得数据,然后渲染到页面。vuex主要是实现组件间数据交换的,调度数据。到此,vue.js就基本实现了所有前端的功能,好像零碎的东西也不少啊,比起wordpress建站神器,确实要复杂蛮多的。不过,相对的,功能也要强不少。

axios

http://www.axios-js.com/zh-cn/docs
https://www.kancloud.cn/yunye/axios/234845
cnpm install axios --save
import axios from 'axios'
methods:{
  get(){
    axios.get('http://vue.studyit.io/api/getlunbo').then(res => {
      console.log(res.data)
    }).catch(function (error) {
      console.log(error)
    })
  }
}

全局设置 main.js
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

vuex

vue配套的公共数据管理工具,它可以把一些共享的数据保存到vuex中
cnpm install vuex --save
import Vuex from 'vuex'
Vue.use(Vuex)
var store = new Vuex.Store({
  state: {
    count: 0  //this.$store.state.count调用数据
  },
  mutations: {
   increment(state){
     state.count ++
   }, //this.$store.commit('increment')调用方法
   getters:  {
      optCount: function (state) {
        return state.count   //只对外提供数据,$store.getters.optCount
      }
   }
  }
})
#挂载到VM实例上
var app = new Vue({
        el: '#app',
        store
      })  

// 总结:
// 1. state中的数据,不能直接修改,如果想要修改,必须通过 mutations
// 2. 如果组件想要直接 从 state 上获取数据: 需要 this.$store.state.***
// 3. 如果 组件,想要修改数据,必须使用 mutations 提供的方法,需要通过 this.$store.commit('方法的名称', 唯一的一个参数)
// 4. 如果 store 中 state 上的数据, 在对外提供的时候,需要做一层包装,那么 ,推荐使用 getters, 如果需要使用 getters ,则用 this.$store.getters.***

网络研习社系列文章:


@lemooljiang #network-institute