gpt4 book ai didi

javascript - 如何定期更新 VueJS 中的组件

转载 作者:行者123 更新时间:2023-12-03 05:13:20 26 4
gpt4 key购买 nike

我在 Vue 中有一个如下所示的组件:

<template>
<div id="featured_top">
<i class="i-cancel close"></i>
<div v-for="item in toplist">
<div class="featured-item" v-lazy:background-image="poster(item)">
<a class="page-link" :href="url(item)" target="_blank">
<h4 class="type"> Featured Movie </h4>
<div class="title">{{ item.title }}</div>
</a>
</div>
</div>
</div>
</template>

<script>
const _ = require('lodash')

export default {
name: 'featured',
computed: {
toplist () {
return _.sampleSize(this.$store.state.toplist, 3)
}
},
methods: {
poster: function (item) {
return 'https://example.com/' + item.backdrop_path
},
url: function (item) {
return 'http://example.com/' + item.id
}
}
}
</script>

在渲染组件时,我从商店中随机选择三个项目,然后进行迭代并显示。然而,这似乎太静态了,所以我想定期更新组件,以便它再次随机化项目。

我是 Vue2 新手 - 关于我缺少哪些琐碎的部分有什么想法吗?

最佳答案

我并不完全清楚您的用例,但如果您想按一定间隔进行随机化。您可以将计算更改为方法并使用 setInterval 调用此函数。

类似于下面的演示或这个 fiddle应该可以。

(在演示中,我删除了图像的延迟加载,以稍微降低复杂性。)

// const _ = require('lodash')
const testData = _.range(1, 10)
.map((val) => {
return {
title: 'a item ' + val
}
})

const store = new Vuex.Store({
state: {
toplist: testData
}
})
//export default {

const randomItems = {
name: 'featured',
template: '#tmpl',
computed: {
/*toplist () {
return _.sampleSize(this.$store.state.toplist, 3)
}*/
},
created() {
this.getToplist() // first run
this.interval = setInterval(this.getToplist, 2000)
},
beforeDestroy() {
if (this.interval) {
clearIntervall(this.interval)
this.interval = undefined
}
},
data() {
return {
interval: undefined,
toplist: []
}
},
methods: {
getToplist() {
this.toplist = _.sampleSize(this.$store.state.toplist, 3)
},
poster: function(item) {
return 'https://example.com/' + item.backdrop_path
},
url: function(item) {
return 'http://example.com/' + item.id
}
}
}

new Vue({
el: '#app',
template: '<div><random-items></random-items</div>',
store,
components: {
randomItems
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.1.1/vuex.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
<div id="app">
</div>

<script type="text/template" id="tmpl">
<div id="featured_top">
<i class="i-cancel close"></i>
<div v-for="item in toplist">
<div class="featured-item" v-lazy:background-image="poster(item)">
<a class="page-link" :href="url(item)" target="_blank">
<h4 class="type"> Featured Movie </h4>
<div class="title">{{ item.title }}</div>
</a>
</div>
</div>
</div>
</script>

关于javascript - 如何定期更新 VueJS 中的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41706938/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com