简体   繁体   English

VueJS 和 Keep-Alive:为什么会出现控制台错误?

[英]VueJS and Keep-Alive: Why the console error?

I have a view/page called posts that I want to show with a list of posts.我有一个名为posts的视图/页面,我想用帖子列表显示。 Let's assume that this page would contain thousands of posts.假设该页面将包含数千个帖子。 Thus, I only want to load it once, and if the user navigates to a different page of the app and then returns back to the posts page, I don't want to make an API call and load all the posts again.因此,我只想加载一次,如果用户导航到应用程序的不同页面然后返回到posts页面,我不想进行 API 调用并再次加载所有帖子。

I saw that Vue has something called <keep-alive> which can cache certain routes/components: https://v2.vuejs.org/v2/api/#keep-alive我看到 Vue 有一个叫做<keep-alive>东西,它可以缓存某些路由/组件: https ://v2.vuejs.org/v2/api/#keep-alive

Here's what I tried:这是我尝试过的:

<keep-alive :include="posts">
    <RouterView :key="$route.name" class="pb-5"/>
</keep-alive>

Unfortunately, I can't figure out why it won't work for my demo.不幸的是,我无法弄清楚为什么它不适用于我的演示。 I get a console error like so:我收到这样的控制台错误:

[Vue warn]: Property or method "posts" is not defined on the instance but referenced during render. [Vue 警告]:属性或方法“posts”未在实例上定义,但在渲染期间被引用。 Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.通过初始化该属性,确保该属性是反应性的,无论是在数据选项中,还是对于基于类的组件。 See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties .请参阅: https ://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties。

found in

---> <App> at /src/App.vue
       <Root>

Anyone have any tips on what I am doing wrong?有人对我做错了什么有任何提示吗? Here's my codesandbox demo: https://codesandbox.io/s/v010-65o4r?fontsize=14&hidenavigation=1&module=%2Fsrc%2FApp.vue&theme=dark这是我的代码框演示: https ://codesandbox.io/s/v010-65o4r?fontsize=14&hidenavigation=1&module=%2Fsrc%2FApp.vue&theme=dark

You need to remove the : binding from include , otherwise it's looking for a data property called posts in your App component instead of the literal string "posts".您需要从include中删除:绑定,否则它会在您的App组件中查找名为posts的数据属性,而不是文字字符串“posts”。

<keep-alive include="posts">
    <RouterView :key="$route.name" class="pb-5"/>
</keep-alive>

You also need to give your Posts component the name "posts", because the keep-alive include refers to a component name and your component doesn't have one:您还需要为您的Posts组件命名为“posts”,因为keep-alive include引用组件名称而您的组件没有:

export default {
  name: "posts",  // <-- Add this
  components: {
    PostsList
  }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM