Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[vue] 22. vue 中 keep-alive 组件的作用 #413

Open
qiilee opened this issue Oct 8, 2019 · 0 comments
Open

[vue] 22. vue 中 keep-alive 组件的作用 #413

qiilee opened this issue Oct 8, 2019 · 0 comments
Labels

Comments

@qiilee
Copy link
Member

qiilee commented Oct 8, 2019

答案:keep-alive 是 Vue 内置的一个组件,可以使被包含的组件保留状态,或避免重新渲染。

解析:

用法也很简单:

<keep-alive>
  <component>
    <!-- 该组件将被缓存! -->
  </component>
</keep-alive>

props
_ include - 字符串或正则表达,只有匹配的组件会被缓存
_ exclude - 字符串或正则表达式,任何匹配的组件都不会被缓存

// 组件 a
export default {
  name: "a",
  data() {
    return {};
  }
};
<keep-alive include="a">
  <component>
    <!-- name 为 a 的组件将被缓存! -->
  </component> </keep-alive
>可以保留它的状态或避免重新渲染
<keep-alive exclude="a">
  <component>
    <!-- 除了 name 为 a 的组件都将被缓存! -->
  </component> </keep-alive
>可以保留它的状态或避免重新渲染

但实际项目中,需要配合 vue-router 共同使用.

router-view 也是一个组件,如果直接被包在 keep-alive 里面,所有路径匹配到的视图组件都会被缓存:

<keep-alive>
  <router-view>
    <!-- 所有路径匹配到的视图组件都会被缓存! -->
  </router-view>
</keep-alive>

如果只想 router-view 里面某个组件被缓存,怎么办?

增加 router.meta 属性

// routes 配置
export default [
  {
    path: "/",
    name: "home",
    component: Home,
    meta: {
      keepAlive: true // 需要被缓存
    }
  },
  {
    path: "/:id",
    name: "edit",
    component: Edit,
    meta: {
      keepAlive: false // 不需要被缓存
    }
  }
];
<keep-alive>
    <router-view v-if="$route.meta.keepAlive">
        <!-- 这里是会被缓存的视图组件,比如 Home! -->
    </router-view>
</keep-alive>

<router-view v-if="!$route.meta.keepAlive">
    <!-- 这里是不被缓存的视图组件,比如 Edit! -->
</router-view>
@qiilee qiilee added the VUE label Oct 8, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant