Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

用了vuex,在action里定义了一个发请求并把数据放在state里方法

actions: {  
    GET_LIST_DATA: ({state },url) => {
      axios.get(url)
      .then(function (response) {
        state.good=response.data.data
        console.log(state.good)

      })
      .catch(function (error) {
        console.log(error);
      });
    }
    
  },

在一个组件的mounted里调用这个action之后获取state

mounted() {
    this.$store.dispatch('GET_LIST_DATA','https://cnodejs.org/api/v1/topics')
      .then(() => {
        this.dataList = this.$store.state.good   
        console.log(this.$store.state.good)
        
      })
  },

页面第一次打开时,执行顺序为请求成功后打印这个state,刷新页面时,请求依然成功了,但state就变成undefined了,不知道是不是请求还没成功就打印了。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
260 views
Welcome To Ask or Share your Answers For Others

1 Answer

箭头函数的this指向问题,换成function就好了,或者用闭包把this保存到变量传入箭头函数里


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...