繁体   English   中英

如何在Vue.js Express MongoDB应用中传递道具

[英]How to pass props in a Vue.js Express MongoDB app

我正在尝试使用Vue.js Node,Express和MongoDB构建基本的聊天应用程序。 我的聊天应用程序有一个欢迎页面,使用户可以在欢迎屏幕中输入他/她的名字。 (请参阅: Welcome.vue )。 然后将用户名重新路由到Posts.vue ,并将用户名作为prop传递到该组件。 Posts.vue ,用户可以创建一条消息,然后将其添加到聊天消息日志中,并按名称和消息进行排列。 到目前为止,我已经成功地启用了名称( this.name )和消息( this.description )通过app.js Express发布到mongoDB。 但是,只有消息( post.description )返回到屏幕。 给定消息的用户名( post.name )根本不会返回到屏幕。 这与将Welcome.vue名称作为Posts.vue的道具传递Posts.vue吗? 有关如何解决此问题的任何建议? 我的代码如下。 谢谢!

Welcome.vue

<template>
  <div class="welcome container">
    <div class="card">
      <div class="card-content center-align">
        <h2 class="teal-text">Welcome</h2>
        <form @submit.prevent="enterChat">
          <label for="name">Enter your name:</label>
          <input type="text" name="name" v-model="name">
          <p v-if="feedback" class="red-text">{{ feedback }}</p>
          <button class="btn teal">Enter Chat</button>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Welcome',
  data () {
    return {
      name: null,
      feedback: null
    }
  },
  methods: {
    enterChat(){
      if(this.name){
        this.$router.push({ name: 'Posts', params: { name: this.name } })
      } else {
        this.feedback = 'You must enter a name to join'
      }
    }
  }
}
</script>

Posts.vue

<template>
  <div class="posts">
    <h2>{{ name }}'s Chat Feed</h2>
    <div class="table-wrap">
      <div class="form">
        <div>
          <textarea rows="15" cols="15" placeholder="DESCRIPTION" v-model="description"></textarea>
        </div>
        <div>
          <button class="app_post_btn" @click="addPost">Add</button>
        </div>
      </div>
      <table>
        <tr>
          <td>name</td>
          <td width="550">Message</td>
          <td width="100" align="center">Action</td>
        </tr>
        <tr v-for="post in posts" :key="post._id">
          <td>{{ post.name }}</td>
          <td>{{ post.description }}</td>
          <td align="center">
            <a href="#" @click="deletePost(post._id)">Delete</a>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>

<script>
import PostsService from '@/services/PostsService'
export default {
  name: 'posts',
  props: ['name'],
  data () {
    return {
      posts: [],
      description: ''
    }
  },
  mounted () {
    this.getPosts()
  },
  methods: {
    async getPosts () {
      const response = await PostsService.fetchPosts()
      this.posts = response.data.posts
      console.log(this.posts)
    },
    async addPost () {
      await PostsService.addPost({
        name: this.name,
        description: this.description
      })
      this.getPosts()
    },
    async deletePost (id) {
      await PostsService.deletePost(id)
      this.getPosts()
    }
  }
}
</script>

app.js

const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const morgan = require('morgan')
var Post = require("../models/post");

var mongoose = require('mongoose');
mongoose.connect('CONNECTION STRING');
var db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error"));
db.once("open", function(callback){
  console.log("Connection Succeeded");
});

const app = express()
app.use(morgan('combined'))
app.use(bodyParser.json())
app.use(cors())

app.get('/posts', (req, res) => {
  Post.find({}, 'title description', function (error, posts) {
    if (error) { console.error(error); }
    res.send({
      posts: posts
    })
  }).sort({_id: -1})
})

app.post('/posts', (req, res) => {
  var db = req.db
  var name = req.body.name
  var description = req.body.description
  var new_post = new Post({
    name: name,
    description: description
  })

  new_post.save(function (error) {
    if (error) {
      console.log(error)
    }
    res.send({
      success: true,
      message: 'Post saved successfully'
    })
  })
})

app.delete('/posts/:id', (req,res) => {
  var db = req.db;
  Post.remove({
    _id: req.params.id
  }, function(err, post){
    if (err)
      res.send(err)
    res.send({
      success: true
    })
  })
})

app.listen(process.env.PORT || 8081)

post.js(猫鼬模式)

var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var PostSchema = new Schema({
  name: String,
  title: String,
  description: String
});

var Post = mongoose.model("Post", PostSchema);
module.exports = Post;

实际上,您根本没有从数据库返回name ,请参阅Post.find的第二个参数。

只需添加一个name

  Post.find({}, 'title description name', function (error, posts) {
    if (error) { console.error(error); }
    res.send({
      posts: posts
    })
  }).sort({_id: -1})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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