我有一个API请求,可以在函数中调用SQL查询。我试图将结果传递给.vue页面。 (使用express-vue)这是api请求
router.get('/search', (req, res, next) => {
var keyword = ("%" + req.query.keyword + "%")
var lat = req.query.lat
var lng = req.query.lng
console.log(keyword, lat, lng)
connection.query('SELECT *, ( 3959 * acos (cos ( radians(?) )* cos( radians( lat ) )* cos( radians( lng ) - radians(?) )+ sin ( radians(?) )* sin( radians( lat ) ))) AS distance FROM job_posting where job_title like ? HAVING distance < 25', [
lat, lng, lat, keyword
], function(err, rows) {
})
res.render('main', {
// data: {
// results
// },
vue: {
meta: {
title: 'Page Title',
},
components: ['myheader', 'myfooter', 'searchform', , 'results']
}
});
})
和Main.vue页面
<template>
<div id="wrap">
<div class="col-md-1"></div>
<div id="main-container" class="container col-md-10">
<myheader></myheader>
<div class="col-md-4"></div>
<div class="col-md-4">
<searchform></searchform>
<results></results>
</div>
<div class="col-md-4 text-center">
</div>
<div class="col-md-1"></div>
</div>
</div>
</template>
我试图将数据传递给此组件results.vue
<template>
<p>Display data</p>
</template>
<script>
export default {
data: function () {
return {
// dogs: 3
}
}
}
</script>
<style lang="css">
</style>
如何传递&#34;行&#34;数据到results.vue页面?
这里是数据来自数据库的方式
[ RowDataPacket {
id: 1,
job_title: 'Software Engineer',
job_desc: '<p>Ayo</p>',
location: 'Akron, OH',
job_type: 'Full-Time',
salary: '',
date_created: 2016-11-23T05:00:00.000Z,
short_desc: 'yyoyo@gmail.com',
apply_url: 'Ayo',
lat: '41.084821',
lng: '-81.515607',
distance: 0 },
RowDataPacket {
id: 2,
job_title: 'Software Engineer',
job_desc: '<p>Ayo</p>',
location: 'Akron, OH',
job_type: 'Full-Time',
salary: '',
date_created: 2016-11-23T05:00:00.000Z,
short_desc: 'yyoyo@gmail.com',
apply_url: 'Ayo',
lat: '41.084821',
lng: '-81.515607',
distance: 0 },
RowDataPacket {
id: 3,
job_title: 'Software Engineer',
job_desc: '<p>Ayo</p>',
location: 'Akron, OH',
job_type: 'Full-Time',
salary: '',
date_created: 2016-11-23T05:00:00.000Z,
short_desc: 'yyoyo@gmail.com',
apply_url: 'Ayo',
lat: '41.084821',
lng: '-81.515607',
distance: 0 } ]
答案 0 :(得分:0)
我不了解express-vue,但我不认为从路由定义中调用API调用是一个好主意。
而是将lat
和lng
参数传递到您的results
组件,然后使用方法或created()挂钩在那里进行API调用。它可以使将来更改API的实现变得容易一些:
res.render('main', {
data: {
lat,
lng,
},
vue: {
meta: {
title: 'Page Title',
},
components: ['myheader', 'myfooter', 'searchform', , '
}
修改强>
如果您确实需要从路由中查询数据,并假设rows
是一个javascript对象数组,则可以在查询的回调中呈现您的组件:
connection.query('SELECT *, ( 3959 * acos (cos ( radians(?) )* cos( radians( lat ) )* cos( radians( lng ) - radians(?) )+ sin ( radians(?) )* sin( radians( lat ) ))) AS distance FROM job_posting where job_title like ? HAVING distance < 25', [
lat, lng, lat, keyword
], function(err, rows) {
res.render('main', {
data: {
results: rows
},
vue: {
meta: {
title: 'Page Title',
},
components: ['myheader', 'myfooter', 'searchform', 'results']
}
next(); // You probably need to call this
})
请勿忘记致电next()
。