简体   繁体   English

Vue.js隐藏当前视口之外的项目

[英]Vue.js hiding of items outside current viewport

I'm making an e-commerce type menu in Vue.js, with items which are divs that contain a fair amount of functionality and images. 我正在Vue.js中制作一个电子商务类型菜单,其中的项目是包含大量功能和图像的div。 Performance is fairly good when rendering about 200 of these items, but when more than that many are added the site begins to perform sluggishly. 当渲染大约200个项目时,性能相当不错,但是当添加的项目数量过多时,该网站的运行就会开始缓慢。

What's the best way to conditionally hide or remove Vue elements from the DOM if they are outside the current scrollable view (like ScrollViews in iOS)? 如果Vue元素在当前可滚动视图之外(例如iOS中的ScrollViews),有条件地从DOM中隐藏或删除Vue元素的最佳方法是什么? Are there any plugins or libraries that can help with the performance of long lists of data items in Vue.js? 在Vue.js中是否有任何插件或库可以帮助执行较长的数据项列表?

Thanks! 谢谢!

I've made a demo snippet using the package I mentioned in my comment. 我已经使用我在评论中提到的软件包制作了一个演示代码段。

I've made a "signal" item that acts as the watcher. 我制作了一个“信号”项来充当观察者。 When the "signal" item leaves the viewport, the "complex-stuff" is no longer rendered. 当“信号”项离开视口时,“复杂材料”不再呈现。 I did it this way so you can see the "complex-stuff" disappear. 我这样做是为了让您看到“复杂的东西”消失。 When the "signal" scrolls back into view, the "complex-stuff" is rendered. 当“信号”滚动回视图时,将显示“复杂材料”。

You could just put the watcher on the widget root element and things will only be hidden when the whole widget is out of view. 您可以将观察者放在小部件的根元素上,并且只有在整个小部件都看不到时,事物才会被隐藏。 You don't want to put the v-if on the root element, though, or it will never come back once it goes away. 但是,您不想将v-if放在根元素上,否则一旦消失就永远不会回来。

 const containerMonitor = scrollMonitor.createContainer(document.body); new Vue({ el: '#app', data: { ids: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] }, components: { widget: { template: '#widget-template', props: ['id'], data() { return { visible: true }; }, mounted() { const elementWatcher = containerMonitor.create(this.$el.querySelector('.signal')); elementWatcher.enterViewport(() => { this.visible = true; }); elementWatcher.exitViewport(() => { this.visible = false; }); } } } }); 
 .widget-container { height: 200px; margin: 10px; background-color: #f0f0f0; display: flex; flex-flow: row wrap; } .signal { height: 10px; width: 10px; margin: 30px; background-color: red; border: thin solid blue; } .complex-stuff { flex-basis: 100%; padding: 15px; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script> <script src="https://rawgit.com/stutrek/scrollMonitor/master/scrollMonitor.js"></script> <template id="widget-template"> <div class="widget-container"> <div class="signal"> </div> <div v-if="visible" class="complex-stuff"> This is widget {{id}}. Blah blah blah. </div> </div> </template> <div id="app"> Widgets below: <widget v-for="id in ids" :id="id"></widget> :widgets above </div> 

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

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