> ## Content Index
> Fetch the complete content index at: https://iiong.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# Vue Cli注入方法
- URL: https://iiong.com/vue-provide-inject-using/
- Published: 2019-11-18T13:23:23.000Z
- Updated: 2026-06-22T15:30:52.000Z
- Description: 使用 Provide/Inject 在子组件注入一个方法，这个方法可以控制 router-view 的显示和隐藏，从而达到页面加载的效果。
- Author: 淮城一只猫
- Tags: 奇技淫巧, Vue.js

### Cap1 使用

使用 [Provide/Inject](https://cn.vuejs.org/v2/api/?ref=iiong.com#provide-inject) 在子组件注入一个方法，这个方法可以控制 `router-view` 的显示和隐藏，从而达到页面加载的效果。

首先在顶级组件里添加方法：

```javascript
<template>
  <div id="app">
    <router-view v-if="isRouterAlive" :key="key"/>
  </div>
</template>
 
<script>
export default {
  name: 'App',
  provide() {
    return {
      reload: this.reload
    };
  },
  data() {
    return {
      isRouterAlive: true
    };
  },
  computed: {
    key() {
      return this.$route.path;
    }
  },
  methods: {
    reload() {
      this.isRouterAlive = false;
      this.$nextTick(() => {
        this.isRouterAlive = true;
      });
    }
  }
};
</script>

```

然后只需要在子组件注入这个方法可以实现：

```javascript
<template>
  <div class="app-container"/>
</template>
 
<script>
export default {
  inject: ['reload'],
  methods: {
    reloadFunction() {
      this.reload();
    }
  }
};
</script>

```

同样可以利用该特性实现别的方法。