在使用服务器端渲染时, 除了服务端的接口缓存, 页面缓存, 组建缓存等, 浏览器端也避免不了要使用缓存, 减少页面的重绘.
这时候我们就会想到 vue 的 keep-alive, 接下来我们说一下 keep-alive 的使用
假如现在我们有两个页面, home.vue 和 about.vue
home.vue
- <pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);"><template>
- <div>
- home
- </div>
- </template>
- <script>
- export default {
- name: Home,
- created() {
- console.log('home)
- }
- }
- </script>
- </pre>
about.vue
- <pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);"><template>
- <div>
- about
- </div>
- </template>
- <script>
- export default {
- name: About,
- created() {
- console.log('home)
- }
- }
- </script>
- </pre>
App.vue 中我们使用 keep-alive 缓存
- <pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232);"><template>
- <div id="app">
- <keep-alive include="Home">
- <router-view class="view">
- </router-view>
- </keep-alive>
- </div>
- </template>
- <script>
- export default {
- name: 'App'
- }
- </script>
- </pre>
这时候运行我们会发现 Home 页面就缓存下来了, 大功告成
所有的问题都是我在日常生活中用到的, 可能会有不正确或者不是最佳解决方案, 希望留下你的建议和意见, 共同学习, 共同进步.
来源: http://www.qdfuns.com/article/51117/e68382c5924164c755896dad0bb2d778.html