vue项目中使用axios配合vuex进行前后台交互
1.下载axios和vuex
npm install --save axios
npm install --save vuex
2.在index.html中输入
<script>
// 设置接口地址
window.sessionStorage.setItem('domain', 'https://api.apiopen.top');
</script>
3.创建store.js文件,并输入
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
//获取接口地址
let shcPost = window.sessionStorage.getItem('domain')
const store = new Vuex.Store({
state: {
shcPost: shcPost,
},
})
Vue.use(store)
export default store
4.在main.js中引入vuex、store、axios
import Vuex from 'vuex'
import store from './store'
import axios from 'axios'
Vue.prototype.$http = axios
Vue.use(Vuex)
new Vue({
el: '#app',
store,
components: { App },
template:'<App/>'})
4.在需要调取接口的页面创建方法
getData () {
this.$http.post(this.$store.state.shcPost+'/getWangYiNews',{
'page':1,
'count':5
}).then(res => {
if(res.data.code == 200) {
console.log(res)
}
}).catch(error => {
console.log(error)
})
}
5.在mounted中调用方法
mounted(){
this.getData()
},