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

4,908 阅读1分钟

起因

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

// 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

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

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

走起

// 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 同上不变
哈哈^_^,数据出现了,不过对象多了一个层级

推荐阅读: