简体   繁体   中英

How to use global variables in Vue JS components?

I'm trying to develop a web-app using Vue JS. Single File components(.vue files) is a nice way to create components but I don't want to use any node modules. And I found https://github.com/FranckFreiburger/http-vue-loader which will allow me to load .vue files directly from my html/js.

I'm trying to populate real-time data from websocket to a html table which is inside a component. Now I want to use the same websocket data for multiple components. I created the websocket and a global variable to store data outside the component(ie, in app.js). Now I used this variable inside my component for real-time data updates. But html table is not getting updated though I'm receiving data.

The idea is to create a single websocket and use the data for multiple components.

I'm actually new to Vue framework so forgive if any understanding issues are there.

Here is my sample code:

index.html

<!DOCTYPE html>
<html>

<body>
  <div id="app">
        <div>
          <comp1></comp1>
          <comp1></comp1>
        </div>
  </div>

  <script src="js/vue.js"></script>
  <script src="js/httpVueLoader.js"></script>
  <script src="js/app.js"></script>
</body>

</html>

app.js

var global_data = [];
var ws = new WebSocket("ws://127.0.0.1:9012/ws");
ws.onmessage = msg => {
   global_data = JSON.parse(msg.data);
   console.log(global_data);
};

new Vue({
  el: "#app",
  components: {
    'comp1': httpVueLoader('js/component1.vue')
  },
  data: {

  }
});

component1.vue

<template>
  <div>
    <table id="tm_table" class="content-table">
      <thead>
        <th>Parameter</th>
        <th>Value</th>
      </thead>
      <tbody>
        <tr v-for="(parameter, id) in rt_data.params" :key="id">
          <td>{{parameter.param}}</td>
          <td>{{parameter.value}}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
module.exports = {
  data() {
    return {
      rt_data: global_data,
    };
  }
};
</script>

<style>
</style>

Any help to solve this problem or even suggestion to any different approach is highly appreciated. Thank you.

Without using Vuex.. You can keep your global variables in the parent component and then just pass them down as props. Alternatively, you can store things in the browser's local storage and then access them from components when you need to. This will kind of act as a way of setting global variables and it's quite widely adopted now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM