[Vuejs]-How to set global data on Vue on runtime?

0👍

There are a few ways to go about this.

I would state the problem as follows: The backend knows about things (like the api baseUrl) and the frontend (javascript application) needs to know about this.

Method 1: Providing data via the window object.

// backend
<div id="app"></div>

<script>
// backendvariable could be a string
// we could even JSON-encode the data

window.APP_CONFIG = <%= backendVariable %>

// alternatively:
window.APP_CONFIG = {
    API_URL: <%= apiUrl %>,
    SOME_CONSTANT: <%= someConstant %>,
    ...
}
</script>
// somewhere in our frontend
const apiUrl = window.APP_CONFIG.API_URL;

Method 2: Supplying data via the Vue instance
When your javascript bundle only contains the defined components but leaves the mounting of Vue up to your backend.

// backend
<div id="app"></div>

<script>
new Vue({ 
   el: '#app',
   data: {
      API_URL: <%= backendVariable %>
   }
});
</script>

now our server variable will be available to all Vue components via this.$root.API_URL (or $root.API_URL inside Vue templates). It wont be available outside the Vue application.

Method 3: Supplying data via the mounting point

// backend
<div id="app" 
   data-api-url="<%= backendVariable %>" 
   config='<%= jsonEncodedData %>' 
></div>

When you try using to add jsonEncodedData you should write single quotes instead of double quotes.

// in your frontend 
new Vue({
   el: '#app',
   mounted() { 
       // This is how we access the externally provided data
       var API_URL = this.$el.getAttribute('data-api-url');

       // it's up to you to put this value accessible to 
       // all the consumers. 

       // You are not limited to scalar values:
       try { 
          var CONFIG = JSON.parse(this.$el.getAttribute('config') || '{}');
       } catch (e) {
           console.error("Invalid json supplied to app: ", e);
           var CONFIG = { }; // default config
       }
   }
});

It’s also possible to JSON.parse()

Method 4: Supplying data via the mounting point template.
We have a javascript bundle that mounts the Vue app to #app.

// backend
// In this case our mounting point also includes a bare template
<div id="app">
   <app v-bind:config='<%= jsonEncodedData %>'></app>
   // or: 
   <app v-bind:config='{"api_url": "value"}'></app>
</div>
import App from './app.vue';
// frontend main
new Vue({
   el: '#app',
   components: { App }
});
// app.vue will receive our json encoded backend-data
// because we did v-bind:config Vue will automatically json-parse the data
// for us. 
<script>
export default { 
    props: ['config']
}
</script>

Again you are free to make this config data available to the rest of your application.

Leave a comment