资讯详情部分作为一个组件
1.封装为组件
创建news-item.vue
<template>
<view>
<view class="news_item" v-for="item in data" :key="item.id">
<image :src="item.img_url"></image>
<view class="content">
<view class="tit">{{item.title}}</view>
<view class="info">
<text>发表时间:{{item.add_time | formatDate}}</text>
<text>浏览:{{item.click+123}}次</text>
</view>
</view>
</view>
</view>
</template>
<script>
export default {
props: ['data'],
filters:{
formatDate(data){
const date = new Date(data)
console.log(date)
const day = date.getMonth().toString().padStart(2,'0')+'-'+date.getDay().toString().padStart(2,'0')
return date.getFullYear()+'-'+day
}
}
}
</script>
<style lang="scss">
.news_item{
display: flex;
padding: 5px 10px;
border-bottom: 1rpx solid $shop-color;
image{
max-width: 200rpx;
min-width: 200rpx;
height: 150rpx;
}
.content {
padding: 5px 10px;
position: relative;
.tit{
font-size: 30rpx;
}
.info{
font-size: 26rpx;
position: absolute;
left: 10px;
bottom: 5px;
text:nth-child(2){
margin-left: 20px;
}
}
}
}
</style>
2.在新闻页面导入并使用
<template>
<view class="news">
<new-item :data="newsList"></new-item>
</view>
</template>
<script>
import newItem from '../../components/new-item/new-item.vue'
export default {
data() {
return {
newsList: []
}
},
methods: {
async getNewsList () {
const res = await this.$myRequest({
url:'/api/getnewslist'
})
this.newsList = res.data.message
}
},
onLoad () {
this.getNewsList()
},
components: {
"new-item":newItem
}
}
</script>
<style lang="scss">
</style>
3.点击列表进入详情
-
点击子组件列表项通过this.$emit触发父组件的方法
navigatorTo (item) { this.$emit('clickItem',item) }
-
父组件通过注册clickItem事件及事件函数实现跳转操作
<template> <view class="news"> <new-item :data="newsList" @clickItem="goDetail"></new-item> </view> </template> <script> export default { methods: { goDetail (data) { console.log(data) uni.navigateTo({ url: '/pages/news-detail/news-detail' }) } } } </script>
-
新建/pages/news-detail/news-detail页面