Vue.js:访问模板字符串中的全局值

Rob*_*Rob 5 javascript vue.js

我有一个非常基本的 Vue.js 应用程序,如下所示:

index.html(只是<body>为了简洁)

<div id="root"></div>
Run Code Online (Sandbox Code Playgroud)

主文件

var config = {
  title: 'My App',
}

new Vue({
  el: '#root',
  template: '<div>{{ config.title }}</div>',
})
Run Code Online (Sandbox Code Playgroud)

这给了我:

Property or method "config" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. 
(found in root instance)
Run Code Online (Sandbox Code Playgroud)

我猜这是因为 Vue 在数据存储中寻找它而不是window. 有什么方法可以表明config这里是全局的,还是有更好的方法来完全做到这一点?我想我可以将配置对象作为道具传递给我的根Vue实例,但似乎只有组件接受道具。感谢您对此的任何见解。

Man*_*ani 6

您可以尝试如下定义您的应用:

new Vue({
  el: '#root',
  template: '<div>{{ config.title }}</div>',
  data: function() {
    return {
      config: window.config
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

在上面的定义中,您this.config在根组件中指向window.config- 全局变量。