简体   繁体   English

如何使用 webpack 和 vue-cli 将服务器端变量发送到 vue 实例?

[英]How to send server-side variables to vue instance using webpack & vue-cli?

I am currently making a project using vue-cli which generates a Node project with webpack.我目前正在使用 vue-cli 制作一个项目,它使用 webpack 生成一个 Node 项目。 I can build all scripts and use the pug language within .vue files.我可以构建所有脚本并在.vue文件中使用.vue语言。 When building, the project uses HTML-Webpack-Plugin , though, which outputs the code as static HTML with client-side scripts.但是,在构建时,该项目使用HTML-Webpack-Plugin ,它将代码输出为带有客户端脚本的静态 HTML。

How do I pass variables from the server-side to these client-side scripts?如何将变量从服务器端传递给这些客户端脚本? I previously was using pug, which made this process easy, but since it now gets built into .html files, this can no longer be done.我以前使用 pug,这使这个过程变得简单,但由于它现在已内置到.html文件中,因此无法再执行此操作。

I have two attempts, both suboptimal:我有两次尝试,都不理想:

1. Send variables into clientside scripts 1. 将变量发送到客户端脚本

script.
  const clinetSideVar = `!{serverSideVar}`;

The problem with this approach is that I cannot pass this variable into the vue instance, since it gets obfuscated when built and I have no way of accessing it (or do I? I haven't found a way).这种方法的问题是我无法将此变量传递给 vue 实例,因为它在构建时会被混淆,而且我无法访问它(或者我无法访问它?我还没有找到方法)。

2. Using AJAX requests 2. 使用 AJAX 请求

I could also make a restful API for server-side site data and retrieve it using AJAX, but this seems like a real hack and this would lose quite a bit of performance over just sending the data plainly through a pug template (with no. 1 I'd too, since client-side JS would have to insert the data into the DOM).我还可以为服务器端站点数据创建一个安静的 API 并使用 AJAX 检索它,但这似乎是一个真正的黑客攻击,并且仅通过 pug 模板(第 1我也是,因为客户端 JS 必须将数据插入到 DOM 中)。

I'd recommend using JSONP (since your index.html is built ahead of time in Vue-cli).我建议使用JSONP (因为您的 index.html 是在 Vue-cli 中提前构建的)。

In your public/index.html (which is a template)在您的 public/index.html (这是一个模板)

<head>
    ...
  <script>function getServerData(data) { window.__SERVER_DATA__ = data; }</script>
  <script src="/api/server-data.json?callback=getServerData"></script>
</head>

In your Node Express routes definition在您的 Node Express 路由定义中

const app = express();

// ...

app.get('/api/server-data.json', (req, res) => {
  res.jsonp({
    foo: 'foo',
    bar: 'bar'
  });
});

Then just access window.__SERVER_DATA__ from within any Vue component.然后只需从任何 Vue 组件中访问window.__SERVER_DATA__

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

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