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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用vuejs从mongodb数据库中读取数据相关的知识,希望对你有一定的参考价值。

我正在创建一个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>
答案

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

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

以上是关于使用vuejs从mongodb数据库中读取数据的主要内容,如果未能解决你的问题,请参考以下文章