【问题标题】:Pass global JSON to Vue app from flask webserver从烧瓶网络服务器将全局 JSON 传递给 Vue 应用程序
【发布时间】:2017-05-08 09:35:40
【问题描述】:

我有一个启用 vue-router 的应用程序,它使用单文件 .vue 组件,使用 browserify 捆绑。这个应用程序由一个烧瓶网络服务器提供服务,它将全局配置设置(页面标题、布局顺序等)作为 JSON 传递给它。我一直在努力以一种干净的方式将全局变量传递到应用程序中。

main.js(作为 browserify 的入口点):

var Content = require('./vue/Content.vue');
var App = Vue.extend();
var router = new VueRouter({ history: true });
router.map({
  '/': { component: Content, name: 'home' }
});
router.start(App, '#app');

index.html,由烧瓶网络服务器提供服务

<body>
{% with ga_id = ''|get_env('GA_ID') %}
  <div id="app" ><router-view ga-id={{ga_id}} global-settings={{globalsettings|tojson|safe}}></router-view></div>
{% endwith %}
  <script type="text/javascript">
    window.global_settings = {{globalsettings|tojson|safe}};
  </script>
  <script src="/js/build.js" defer></script>
</body>

App.vue,应用的主要组件:

<template>
</template>
<script type="text/javascript">
  var app = {
    props: ['gaId', 'globalSettings'],
   ready: function ready() {
      console.log(this.gaId); //returns expected string
      console.log(this.globalSettings); //truncated at first space in the string
      console.log(window.global_settings); // returns expected json
    },
  module.exports = app;
</script>

为了完整起见,routes.py:

@APP.route('/', methods=['GET'])
def index():
    settings = APP.app_config['settings']
    return render_template('index.html', rawsettings=settings)

通过在window上设置给Vue传递一个全局变量感觉不对,但是我一直无法传递它。

我尝试在main.js中使用Vue.extend中的数据函数:

Vue.extend({ 
  data: function() {
    return { 
      global: 'test' 
    }
  }
})

this.globalApp.vue 中未定义。我应该使用更好的模式吗?

【问题讨论】:

    标签: javascript vue-router vue.js


    【解决方案1】:

    来自 Vue.js 官方 API 文档的This feature 意味着在任何组件内部,this.$root 将引用根 Vue 实例,或者,在您的情况下,是 App 变量。

    因此,理想情况下,您希望更改这一行:

    window.global_settings = {{globalsettings|tojson|safe}};
    

    App.global_settings = {{globalsettings|tojson|safe}};
    

    然后您可以使用this.$root.global_settings 从任何组件访问global_settings

    但是,根据您的代码捆绑方式,App 可能会在全局范围内返回 undefined。这让我完全想到了一个更好的观点......

    考虑使用 vuex

    vuex 是 vuejs 的官方状态管理器。基本上,它作为所有组件共享状态(或数据)的中心,非常符合“全局设置”的概念! Vuex 还具有非常强大的功能,尤其适用于大型应用程序。但是,如果您不打算广泛使用 vuex,那么像我之前的方法可能更可取或更轻量级。

    【讨论】:

    • 我正在研究 vuex。但我的问题仍然存在 - 我如何将这些数据从 flask 获取到 vuex 开始?
    • 如果我们决定使用 vuex,您能解释一下如何将数据导入 vuex 吗?
    猜你喜欢
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    • 2013-03-25
    • 2022-01-25
    相关资源
    最近更新 更多