简体   繁体   English

如何将数据从 express 的渲染传递到 vue 组件?

[英]How to pass data from express's render to vue component?

Given an express route,给定一条快速路线,

page.js页面.js

router.post('/results', (req, res, next) => {
    output.terms  = "hello"
    output.results = [{"text": "hello world"}, {"text": "hello sunshine"}]
    res.render("/myview",output)    
})

The following works and shows the text.以下工作并显示文本。

myview.pug myview.pug

extends ../layout.pug

block content
    each result in results
        span=result.text

But the following vue component doesn't.但是下面的 vue 组件没有。 I receive TypeError: results is undefined我收到TypeError: results is undefined

results-view.vue结果视图.vue

<template lang="pug">
    li(v-for='result in results')
        span {{ result.text }}
</template>

<script>
    export default {
        ...
    }
</script>

myview.pug myview.pug

extends ../layout.pug

block content
    results-view

How do I pass the data from router to vue component?如何将数据从路由器传递到 vue 组件?

You should probably think of some other solution. 您可能应该考虑其他解决方案。 It does not make sense to pass data from route to component. 将数据从路线传递到组件没有意义。 You can create an API endpoint that returns data and in Vue you can access it via request. 您可以创建一个返回数据的API端点,在Vue中,您可以通过请求进行访问。

In the end, this worked. 最后,这奏效了。 Might not be the best practice (I'm not sure, really) as warned by commenter serkan 评论员serkan警告说,这可能不是最佳做法(我不确定,确实如此)

results-view.vue results-view.vue

<template lang="pug">
    li(v-for='result in results')
        span {{ result.text }}
</template>

<script>
    export default {
        name: 'results-view',
        props: ['results']
        ...
    }
</script>

myview.pug myview.pug

extends ../layout.pug

block content
    results-view(results=results)

There are times when it makes sense to pass data from the router to your frontend component.有时将数据从路由器传递到前端组件是有意义的。 No need to write an API and fetch that data in another roundtrip.无需编写 API 并在另一次往返中获取该数据。

const customer = { id: '123', name: 'Jojo Sasa' }
res.render('customer/detail', { customer })

customer/detail.pug客户/详细信息.pug

// This will define customer as a global variable
script window.customer= !{JSON.stringify(customer)}

//The below code will run in the browser
script.
  // This code will run in the browser
  alert(`Customer is: ${cutomer.name}`)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM