【发布时间】:2019-04-23 18:56:14
【问题描述】:
我正在 vue 中创建一个基本应用程序,它使用 axios 发出获取请求以从博客站点获取 html 数据,并使用 cheerio node package 来抓取站点中的元素,例如博客标题和每个站点的发布日期博客文章。但是,我在尝试将抓取的元素呈现到 html 中时遇到了麻烦。代码如下:
<template>
<div class="card">
<div
v-for="result in results"
:key="result.id"
class="card-body">
<h5 class="card-title">{{ result.title }}</h5>
<h6 class="card-subtitle mb-2 text-muted">{{ result.datePosted }}</h6>
</div>
</div>
</template>
<script>
const Vue = require('vue')
const axios = require('axios')
const cheerio = require('cheerio')
const URL = 'https://someblogsite.com'
export default {
data() {
return {
results: []
}
},
mounted: function() {
this.loadBlogs()
},
methods: {
loadBlogs: function() {
axios
.get(URL)
.then(({ data }) => {
const $ = cheerio.load(data)
let results = this
$('.post').each((i, element) => {
const title = $(element)
.children('.content-inner')
.children('.post-header')
.children('.post-title')
.children('a')
.text()
const datePosted = $(element)
.children('.content-inner')
.children('.post-header')
.children('.post-meta')
.children('.posted-on')
.children('a')
.children('.published')
.text()
this.results[i] = {
id: i + 1,
title: title,
datePosted: datePosted
}
})
})
.catch(console.error)
}
}
}
</script>
我尝试声明
let results = this
在 axios 请求引用导出默认范围内的范围之前,但仍从 VS Code 中获取范围仍在 loadBlogs 函数内的指示符。我错过了什么吗?我非常感谢您的帮助!谢谢!
【问题讨论】:
标签: vue.js axios nuxt.js cheerio