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

时间:2016-12-13 17:21:33

标签: javascript vue.js

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

index.html (只是简洁的<body>

<div id="root"></div>

main.js

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

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

这给了我:

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)

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

2 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分:0)

如果您只是尝试将 App Name 作为硬编码字符串传递,您可以执行以下操作:

var nameMyApp = new Vue({
  el: '#root',
  data: { input: 'My App' },
  computed: {
    whosapp: function () {
      return this.input
    }
  }

})

使用你喜欢的HTML:

<div id="root">
  <div v-html="whosapp"></div>
</div>

输入的值传递给 whosapp div。

但是,如果您正在寻找更具活力的东西,那么这就是要走的路:

使用与上面相同的HTML ...

var nameMyApp = new Vue({
  el: '#root',
  data: { input: 'My App' },

初始值设置为My App,如果未通过方法的函数调用更改,则显示该值。

    methods: {
    update: function(name) {
        this.input = name;
    }
  },

这里是我们定义一个方法的地方,该方法在调用时传入参数以更新this.input。

  computed: {
    whosapp: function () {
      return this.input
    }
  }

})

nameMyApp.update("New Name");

这是我们调用函数的地方,给它新的参数;确保参数是一个字符串。

我希望这是你正在寻找的。