Send all-encompassing JSON data to Vue application from flask server

In my application, I am using vue-router with single-file components in the .vue format. These components are bundled using browserify and served by a flask webserver which provides global configuration settings such as page title and layout order in JSON format. However, I have been facing challenges in cleanly passing these globals into the app.

The entry point for browserify is main.js:

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, which is served by the flask webserver:

<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>

Main component of the app, 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>

For completeness, here is routes.py:

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

I feel uneasy about setting a global variable on the window object to pass it to Vue. I have attempted setting it through the data function in Vue.extend in main.js:

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

However, this.global is undefined in App.vue. Is there a more appropriate pattern I should be following?

Answer №1

This particular functionality outlined in Vue.js's official API documentation indicates that within any component, this.$root will point to the root Vue instance, or, in this scenario, the App variable.

Thus, it is recommended to modify the following line:

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

to

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

allowing access to global_settings from any component using this.$root.global_settings.

It's worth noting that depending on how your code is packaged, App may be undefined in the global scope. This brings us to an even better suggestion...

Consider Implementing Vuex

Vuex serves as the official state manager for vuejs. Essentially acting as a centralized hub for shared state (or data) among all components, which aligns well with the concept of "global settings"! Moreover, Vuex offers robust features tailored for large-scale applications. However, if you have minimal intentions of extensively utilizing vuex, then opting for a lighter approach like the previously mentioned one may be more suitable.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The asynchronous loading of ECMAScript modules using the `import()` function from CommonJS

I have been attempting to utilize a specific npm package called ESM. To reference this package, please visit https://www.npmjs.com/package/key-did-resolver After installing the 'key-did-resolver' package, I encountered difficulty requiring it du ...

Vue 3 - unable to connect attributes to any element

Can you assist me in understanding how to bind attributes with Vue 3? I have an app that functions well on its own, but when I incorporate it into XML <content type="html>" VUE APP </content>, the bindings do not work as expected. T ...

Comparison of Web Development Techniques: localStorage versus Cached HTTP

Imagine a scenario where there is a web server responding to a GET request by sending a .json file. The response instructs the browser to cache it for a period of 5 years. Furthermore, picture a webpage that initiates this GET request for the JSON data du ...

Error in React Native JS: Cannot call the `map` function on variable `l`

Recently diving into the world of Js and React, I am tasked with creating an application for Macronutrients in my second semester project. The challenge I'm facing is incorporating a Pie Chart that displays the values from my state. To implement the ...

What could be causing the `project.addSourceFilesAtPaths("../../tsconfig.json");` function to not retrieve the expected source files?

Using ts-morph to locate all the source files is crucial. The code snippet below demonstrates this: The key code for this operation is as follows: let tsmorph = require('ts-morph') const project = new tsmorph.Project(); project.addSourceFiles ...

Issue with AngularJS not loading dynamically

I'm excited to give AngularJS a try because it seems very promising. In my current application, I am using fancybox to load my pages like this: $.fancybox({ 'href' : 'pages/example.php', 'type' : 'ajax&apos ...

Is it possible to create static IDs in Vue.js?

I'm looking into setting up Automated Testing for a Vue.Js application I am working on. Does anyone know if Vue.js provides a built-in method to generate static identifiers like id or name? ...

Tips for recalling the active URL you just clicked on - is it in JavaScript or PHP?

I currently have an HTML select list menu in place. When a user selects an option, they are redirected to the corresponding page. For example, if they select "Faizabad" from the menu, they will be redirected to http://example.com/towns/Faizabad. The menu b ...

JavaScript URLs

Check out this cool geo-targeting JavaScript code snippet: <script src='http://promos.fling.com/geo/txt/location.php?testip='></script> Can we incorporate the results from this code into the end of a URL? <a href="http://www.exa ...

Yup validation may not accurately validate every field

I am facing an issue with validating a form using yup. The problem arises when I attempt to iterate over the errors thrown by yup, as I discovered that the last field I enter does not get validated: const schema = yup.object().shape({ age: yup. ...

Waiting for the response of a Javascript function

I have the code snippet below: myFunc(); bar(); The function myFunc() initiates an ajax request. I want to ensure that bar() is only executed after myFunc()'s ajax request has been completed. However, I do not wish to move the call to bar() inside ...

Compressing tool combining Google App Engine with Angular JS

Seeking advice on setting up a minifier, like Google Closure, to integrate with Google App Engine. I am using AngularJS for the client side and have multiple JS files that I want to serve as one minified file during production. How can I achieve this witho ...

Tips on stopping Firefox from automatically scrolling to the bottom of the page when a large popup appears

One of the challenges I'm encountering in my application is that, when using a simple onClick event to show a popup with a large size, the page automatically scrolls down to the bottom after the popup appears. This issue seems to be specific to the Fi ...

"amCharts Version 4 introduces a new feature allowing for the month format to be displayed on the Date

When setting up my XYChart, I am facing an issue with the x-Axis labels. I want to display the twelve months from Jan to Dec, but in the image provided, the first month is also showing the Year (yyyy) along with it. let dateAxis = chart.xAxes.push(new ...

Half of the time, the Ajax request is returning the entire page

I have a dropdown select box in HTML that contains around 20 different number codes (e.g. "123456790") as options. When a selection is made, it triggers an Ajax POST request to update the text of a specific HTML element. The code looks like this: HTML &l ...

Why am I unable to utilize JavaScript with the traditional method, despite using Ajax and jQuery Ajax?

As I delve into learning about ajax, I came across an interesting issue related to including JavaScript in the document I link to or open. xmlhttp.open("GET","ajax_info.txt",true); I noticed that when using regular javascript ajax call, the script doesn& ...

Rendering a Three JS model using the gltf loader in Django

I am attempting to integrate a Three JS model into a Django app running on my local environment using version 3.0.3. Here is the template: <script> var model_address ="{% static 'models/matilda/scene.gltf' %}"; // Pass this variable t ...

Prevent divs from flashing by utilizing CSS styling techniques

Is there a way to display two divs at the same position sequentially on hover, using only CSS? .showme{ opacity:0; transition-property:opacity; transition-delay:1s; } .showhim:hover .showme{ opacity:1; transition-property:opacity; ...

New to Angular: I'm getting the error message "tsc is not recognized as an internal or external command" - Help Needed

I am completely new to Angular, so please pardon my lack of knowledge. I encountered an error: C:\Users\Tijl Declerck\Desktop\projects\AngularTestApp\ts-hello>tsc main.ts "tsc" is not recognized as an internal or external ...

The duration for which an API Access Token remains valid is extremely brief

I recently started working with APIs and my current project involves using the Petfinder API v2 to develop a website that allows users to search for adoptable animals. The API utilizes OAuth, requiring a key and secret to obtain a token via CURL. However, ...