刚学vue,在做一个简单的异步请求豆瓣数据+分页器,用的vue-resource。但是在过程中遇到了问题,如何在vuex的store.js中获取这个组件的vue实例,代码如下:
app.vue
import Vue from 'vue'
import $ from 'jquery'
import { mapActions } from 'vuex'
import { mapMutations } from 'vuex'
import bootPage from './components/BootPage.vue'
export default {
data () {
return {
}
},
components:{
bootPage
},
mounted: function () {
console.log(this)
this.$http.jsonp('https://api.douban.com/v2/movie/top250?count=10', {}, {
headers: {
},
emulateJSON: true
}).then(function (response) {
// 这里是处理正确的回调
this.$store.state.articles = response.data.subjects
// this.articles = response.data["subjects"] 也可以
}, function (response) {
// 这里是处理错误的回调
console.log(response)
})
},
methods: {
getList: function () {
this.$http.jsonp(
'https://api.douban.com/v2/movie/top250?count=' + this.$store.state.count,
{count: this.$store.state.count},
{
headers: {
},
emulateJSON: true
}
)
.then(function (response) {
this.$store.state.articles = response.body.subjects
this.$store.state.articles = this.$store.state.articles.slice(-10)
console.log(response)
// this.articles = response.data["subjects"] 也可以
}, function (response) {
// 这里是处理错误的回调
console.log(response)
})
},
}
}
</script>
BootPage.vue
import { mapMutations } from 'vuex'
export default {
data () {
return {
}
},
methods: mapMutations([
'onPageClick',
'onPrevClick',
'onNextClick',
'onFirstClick',
'onLastClick'
])
}
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
title: 'Resource',
name: '豆瓣电影排行榜',
onOff: false,
cur: 1,
pageTotal: 10,
activeNum: 0,
articles : '',
count: 10
}
const mutations = {
onPageClick (state,index) {
state.activeNum = index
},
// 上一页
onPrevClick (state) {
if(state.activeNum <= 0){
return false
}else{
state.activeNum --
}
},
// 下一页
onNextClick (state) {
if(state.activeNum >= state.pageTotal - 1){
return false
}else{
state.activeNum ++
}
},
// 第一页
onFirstClick (state) {
state.activeNum = state.cur - 1
},
// 最后一页
onLastClick (state) {
state.activeNum = state.pageTotal - 1
},
getList (state) {
console.log(this)
this.$http.jsonp('https://api.douban.com/v2/movie/top250?count=10', {}, {
headers: {
},
emulateJSON: true
}).then(function (response) {
// 这里是处理正确的回调
state.articles = response.data.subjects
// this.articles = response.data["subjects"] 也可以
}, function (response) {
// 这里是处理错误的回调
console.log(response)
})
}
}
const store = new Vuex.Store({
state,
mutations
})
export default store
现在在store.js中this指向是undefined,想获取在app.vue中写的getList函数,就要获取组件vue实例,请教各位大神如何获取,求助啊/(ㄒoㄒ)/~~
(PS:我也想过在store.js中注册getList函数,但是getList函数的this.$http还是需要获取vue实例)
在ajax回掉中添加callback;
methods:{
ajax回掉:function(){
}
}