Vue provide inject 传递异步请求的数据(axios)

原由

本萌新在写项目时遇到上层组件须要跨多级组件向后代组件通讯的状况,若是用props逐层传递未免过于麻烦,再加之想要传递的数据并非多个组件共享的因此又排除了Vuex,再一想就是一对官方不推荐使用的API了(provide/inject)。由于坚信官方不推荐使用的必定是牛X的方法,因此在项目中想使用它来半个B。不用不知道,一用吓一跳,玩崩了wocvue

// App.vue
<template>
  <div id="app">
    {{res}}
    <Inject />
  </div>
</template>

<script>
import Inject from "./components/inject.vue";
import "./mock/mockServer";
import axios from "axios";

export default {
  name: "app",
  components: {
    Inject
  },
  data () {
    return {
      res: {}
    };
  },
  provide () {
    return {
      res: this.res
    }
  },
  created () {
    this.getRes()
  },
  methods: {
    getRes () {
      axios.get("/mock").then(res => {
        console.log(res)
        this.res = res.data
        // this.$set(this.res, 'list', res.data)
      })
    }
  }
}
</script>

// inject.vue
<template>
  <div>Inject obj: {{ res }}</div>
</template>

<script>
export default {
  inject: ['res']
}
</script>
复制代码

运行结果出乎意料,inject.vue中没有接收到res

各类百度也没有找到合适的答案ios

几天后有小伙伴提醒能够使用Vue.set这个API实现 官方文档axios

走起

// App.vue
<template>
  <div id="app">
    {{res}}
    <Inject />
  </div>
</template>

<script>
import Inject from "./components/inject.vue";
import "./mock/mockServer";
import axios from "axios";

export default {
  name: "app",
  components: {
    Inject
  },
  data () {
    return {
      res: {}
    };
  },
  provide () {
    return {
      res: this.res
    }
  },
  created () {
    this.getRes()
  },
  methods: {
    getRes () {
      axios.get("/mock").then(res => {
        console.log(res)
        // this.res = res.data
        this.$set(this.res, 'list', res.data) // #####只有这里发生了改变#####
      })
    }
  }
}
</script>
// inject.vue 同上不变
复制代码
哈哈^_^,数据出现了,不过对象多了一个层级

推荐阅读:api

相关文章
相关标签/搜索