爱凉拌菜真是太好了

使用Vue搭建博客(三)——前端文章渲染

首先从服务器请求articles数据,并使用vuex管理

article-list.vue组件中引入articles的Getter,然后使用v-for 将 articles 渲染一遍就行

1
2
3
4
5
6
7
8
9
10
11
//article-list.vue
<article v-for="(item, index) in articles" key={index} class="typo">
<div class="cover" :style="{backgroundImage: ``}"></div>
<header>
<h2 @click="readMore(item)">{{item.title}}</h2>
<h4>{{new Date(item.time).toLocaleString()}}</h4>
</header>
<div v-html="item.abstract" class="article-content">
</div>
<footer @click="readMore(item)">继续阅读</footer>
</article>
1
2
3
4
5
6
7
export default {
computed: {
...mapGetters([
'articles'
])
}
}

接下来就是书写 article 的样式了。不过需要注意的一点是如果 style 使用了 scoped ,那么v-html中的被渲染的那一部分是不能被scoped中的css选择符匹配的。

也就是说不能这样写

1
2
3
4
5
6
7
<style lang="less" scoped>
.article-content {
p { /*这个样式将不生效*/
margin-bottom: 1.5em;
}
}
</style>

而是应该这样写

1
2
3
4
5
6
7
<style lang="less">
.article-content {
p {
margin-bottom: 1.5em;
}
}
</style>

其实文章详情组件article.vue书写方式和article-list.vue也差不多, 只不过 article-content 的v-html内容从abstract(文章概括)变成了content(正文)

1
2
3
4
5
6
7
8
9
10
11
12
13
//article.vue
<article class="typo">
<div class="cover" :style="{backgroundImage: `url(${bgImg})`}"></div>
<header>
<h2>{{currentArticle && currentArticle.title}}</h2>
<h4>{{currentArticle.time && new Date(currentArticle.time).toLocaleString()}}</h4>
<p class="tag">
<span v-for="(tag, index) in currentArticle.tags">{{tag}}</span>
</p>
</header>
<div v-html="currentArticle && currentArticle.content" class="article-content" ref="content">
</div>
</article>