本文是受多篇類似博文的影響寫成的,內容也大致相同。無意抄襲,只是為了總結出一份自己的經驗。
一直以來,在使用Vue進行開發時,每當涉及到前后端交互都是在每個函數中單獨的寫代碼,這樣一來加大了工作量,二來代碼零散復用度不高,修改時要多處修改,漏一處就出問題,三來滿足於一種簡單的方式不利於深入研究技術。現在做項目需要修改使用Vuex+axios發送請求的代碼時,也是把原來的代碼改為自己的“保留技術”,這樣很不好,所以得研究一下如何在Vue項目中更好的與后台交互。
1、修改原型鏈的方案
// main.js import axios from 'axios'; // 引入axios Vue.prototype.$ajax = axios; // 修改原型鏈 // componnentName.vue methods: {
getData () {
this.$ajax.get('/user-list').then( res => {
console.log(res) }).catch(err => { console.log(err) })
} }
2、Vuex結合axios封裝一個action的方案
// main.js import store from './store/'; // 方案二:結合Vuex封裝一個action new Vue({ el: '#app', router, store, // 方案二:結合Vuex封裝一個action components: { App }, template: '<App/>' }) // store/index.js import Vue from 'vue'; import Vuex from 'vuex'; import axios from "axios"; Vue.use(Vuex); const store = new Vuex.Store({ state: { // 初始化數據,只要有可能的用到的最好都初始化
text: {name: 'xxx'}, data: {} }, mutations: { changeData (state, obj) { // store中的數據只能通過commit mutation來改變 state.data = obj } }, actions: { // 封裝一個ajax方法 saveForm (context) { axios.get('./b2b/captcha/img-captcha'}, context.state.test).then(res => { // 調用接口 context.commit('changeData', res.data) // 通過接口獲取的后台數據保存到store中,等待組件取用 }) } } }) export default store; // componentName.vue
computed: {
data () { // 獲取store里的數據,放在computed中可以實時更新
return this.$store.state.data;
}
}, methods: { getDataVuex () { this.$store.dispatch('saveForm'); // 觸發actions里的saveForm函數,調動接口 }, }
上述兩種方案是相互獨立的,也就是說,即使在main.js中引入了axios並修改了原型鏈,在store/index.js中也不能直接使用this.$ajax,而是要引入axios后再使用。
3、回調函數中的this指向問題
回調函數如果是箭頭函數,那么箭頭函數內部的this會自動獲取所在上下文的this值,作為自己的this值。在Vue項目中,this會指向當前的組件實例。
data () { return { a: 123 } }, methods: { getDataVuex () { this.$store.dispatch('saveForm').then(res => { // 回調函數是箭頭函數 console.log(this.a); // --> 123 }) }, }
如果回調函數是普通函數,那么普通函數中this指向的不是組件實例,所以得進行一些處理才能讓this指向當前的組件實例。
data () { return { a: 123 } }, methods: { getDataVuex () { this.$store.dispatch('saveForm').then(function(res) { // 回調函數是普通函數 console.log(this.a); // --> Cannot read property 'msg' of undefined }) }, }
// 解決方案如下:
getDataVuex () {
var _vm = this;
_vm.$store.dispatch('saveForm').then(function(res) { // 回調函數是普通函數
console.log(_vm.a); // --> 123
}) }
// 或:
getDataVuex () {
this.$store.dispatch('saveForm').then(function(res) { // 回調函數是普通函數
console.log(this.a); // --> 123
}.bind(this))
}