使用vuejs从mongodb数据库中读取数据

问题描述 投票:1回答:1

我正在创建一个Web应用程序来实时显示我房间的温度。目前我用raspberry读取值,然后加载数据库mongodb。现在要在我的浏览器上实时显示它我该怎么做?我正在使用node.js和vue.js以及express。如何实时将值传递给vue.js?

var App = Vue.component('App',{
    template: "<h1> {{title}} </h1>",
    data() {
    
        let test= "hello";
        return {title: test};
    }
});

new Vue({
    el:"#app"
});
<div id="app">
   <App></App>
</div>
node.js mongodb express vue.js
1个回答
1
投票

您在后端的代码应该是这样的:

//get the value from db
//create a variable tmp that will receives temperature from db
let tmp;


var router = express.Router();
router.get('/temperature', function(req, res) {
  res.json({
    temperature: tmp
  });
});


app.use('/api', router);

在前面你可以访问该api:

本地主机:8080 / API /温度

使用axios你可以打电话给你的后端并实时恢复温度

var App = Vue.component('App', {
  template: "<h1> {{temperature}} </h1>",
  data() {


    return {
      temperature: 0
    };
  },
  created: function() {

    this.fetchTemp('api/temperature');

    setInterval(()=> {
      this.fetchItems('api/temperature');
    }, 500);
  },

  methods: {

    fetchTemp(uri) {

      axios.get(uri).then((res) => {
        this.temperature = res.data.temperature;
      });
    },
  }
});

I tried to simulate your use case by getting the current time from REST API and show it every second 

new Vue({
  el: '#app',
  data() {
    return {
      now: 0
    };
  },
  created: function() {

    this.fetchTemp('https://script.googleusercontent.com/a/macros/esi.dz/echo?user_content_key=ypoXRw1nVHj-h1VRDmh6TXSI1VpIPWW7Qo2n9El6RqoxAJ3v28nBI9bDY_4UAE0TQJ3pSozxpbTiRvFpmD8pvcTkGSnPAtgRm5_BxDlH2jW0nuo2oDemN9CCS2h10ox_nRPgeZU6HP_B2BW4qWwVPUuHIcJ3mEdrfLIfNZsYUQi0c--vxV_3BX606CngcowlqSfFH8SSiqMPrUuXDMsd72r-P39_jlVDMh0BMLnMwXU02UuEHWiuob4ULL2SJgrtyBAf43AAwP8&lib=MwxUjRcLr2qLlnVOLh12wSNkqcO1Ikdrk');

    setInterval(() => {
      this.fetchTemp('https://script.googleusercontent.com/a/macros/esi.dz/echo?user_content_key=ypoXRw1nVHj-h1VRDmh6TXSI1VpIPWW7Qo2n9El6RqoxAJ3v28nBI9bDY_4UAE0TQJ3pSozxpbTiRvFpmD8pvcTkGSnPAtgRm5_BxDlH2jW0nuo2oDemN9CCS2h10ox_nRPgeZU6HP_B2BW4qWwVPUuHIcJ3mEdrfLIfNZsYUQi0c--vxV_3BX606CngcowlqSfFH8SSiqMPrUuXDMsd72r-P39_jlVDMh0BMLnMwXU02UuEHWiuob4ULL2SJgrtyBAf43AAwP8&lib=MwxUjRcLr2qLlnVOLh12wSNkqcO1Ikdrk');

    }, 1000);
  },

  methods: {

    fetchTemp(uri) {

      axios.get(uri).then((res) => {
        this.now = new Date(res.data.fulldate).toLocaleString();


      }).catch(err => {});
    }
  }
})
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title></title>
  <script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="https://unpkg.com/[email protected]/dist/vue-axios.min.js"></script>
</head>

<body>
  <div id="app">
    <h1> Now : {{now}} </h1>
  </div>
</body>

</html>
© www.soinside.com 2019 - 2024. All rights reserved.