我想显示来自Google警报供稿的一系列文章。我让它在Javascript中工作。如何将前端转换为Vue.js组件并将其显示在Vue.js应用程序上?我的后端是否也必须进行重大更改,或者我可以使用rss.render(组件名称)在Vue.js前端上显示文章?
这里是代码:
客户:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Test page</title>
</head>
<body>
<section>
<h1>Latest articles</h1>
<div class="feed"></div>
</section>
<!-- Load the socket.io-client library -->
<script src="/socket.io/socket.io.js"></script>
<!-- Load JQuery -->
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.slim.min.js">
</script>
<script type="text/javascript">
// Websocket connection
const socket = io();
socket.on('feed', data => {
for (const [i, item] of data.feed.entries()) {
let itemContainer = $('<span></span>')
.addClass('feed__content')
.append(`<p>${i + 1}) ${item.title}<p>`)
.append(`<p>${item.link}</p>`)
.appendTo('.feed');
}
});
</script>
</body>
</html>
后端
const feedparser = require('feedparser-promised');
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const fs = require('fs');
server.listen(8000);
console.log('Server started on localhost:8000');
let url = 'https://www.google.ie/alerts/feeds/10663948362751557705/4511034072220974544';
// Declare a variable for the feed content
let feed = [];
// Parse the feed
feedparser.parse(url).then(items => {
// Update the variable with the new data
for (const [i, item] of items.entries()) {
// Retrieve the ten first elements, with their title and description
// And add them to the feed array
if (i < 9) {
feed.push({
title: item.title,
link: item.link
});
}
}
// Write it to a file so you can know how to parse it better
// The callback is mandatory, but it's useless here
fs.writeFile('feed.json', JSON.stringify(items, null, 2), 'utf-8', (data) => {});
});
// Define the default route
app.get('/', (req, res) => {
// Render the page
res.render('test.ejs');
// Send the data to the client using socket.io
io.on('connection', io => {
io.emit('feed', {
feed: feed
});
});
});
Vue.component('feed', {
template: '#feed-template',
props: ["feed"]
});
new Vue({
el: "#app",
data() {
return {
feeds: []
}
},
mounted() {
//uncomment below to subscribe to socket
//this.subscribeToFeed();
//for demo purposes
this.pretendFeed();
},
methods: {
pretendFeed() {
setInterval(() => {
this.feeds.push({
title: `Feed ${this.feeds.length}`
});
}, 2500);
},
subscribeToFeed() {
const socket = io();
socket.on('feed', data => {
data.feed.entries().forEach(feed => {
this.feeds.push(feed);
});
});
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<ul>
<feed v-for="feed in feeds" :feed="feed" :key="feed.title"></feed>
</ul>
</div>
<script type="text/x-template" id="feed-template">
<li>
{{feed.title}}
</li>
</script>