Easy blog back office systems express + vue-cli + element-ui + mongodb

Technology stack: vue + element + express + mongodb

Tutorial: b station "full-stack summit"

github Address: https://github.com/frotage/vue-management

Preface: I usually write front-end, this is mainly want to learn about the express, and to achieve front-end interface of the element are mainly used to directly call, there is no detailed written especially

specific:

  • mongodb installation

Official website to download after installation, setting data address, did not go backstage set to start automatically, select cmd to open two

Online tutorials is more telling, not repeat them

Cmd open the way two modes:

First open a cmd

mongod --dbpath D:\mongodb\data\db

To open a cmd

mongo

over

  • Vue-cli front end to create a project
vue create the project name

Select when the router plus create

vue add element

Select the time to choose a global installation, do not use a re-registration of a later period

App.vue main interface with element-ui in the container structures

Sidebar leave two

 

 

The folder views delete the original, the new file

CreateArticle.vue => New articles 
EditArticle.vue => edit articles
ListArticle.vue => Article list

The App.vue two key index adjustment as follows:

<el-menu-item index = "/ articles / create"> New article </ el-menu-item> 
<EL-the MENU-Item index = "/ Articles / index"> Article List </ el-menu-item>

Open the router inside index.js

In just three vue views created inside introduced

Set the corresponding three routes vue

  // just open the page of the list when the lead article 
{
  path: '/',
  name: 'Home',
  redirect: '/ Articles / index'
},
// list of articles
{
  path: '/ Articles / index',
  name: 'List-article This article was',
  Component: ListArticle
},
// create an article
{
  path: '/ articles / Create',
  name: 'Create-article This article was',
  Component: Createarticle
},
// id articles based on the article to edit the automatically generated
{
  path: '/ Articles /: ID / Edit',
  name: 'Edit-Article This article was',
  Component: EditArticle
}
CreateArticle.vue

With the form element

In <el-form> a method is provided for the information input to the rear end of post

@submit.native.prevent="saveArticle"

In <el-form> on binding:model="article"

Title and then in the article corresponding to the content <el-input> on, respectively, plus

v-model="article.title"
v-model="article.body"

Creating the data inarticle:{}

ListArticle.vue

A table element of

In <el-table> inside with:data="articles"

EditArticle.vue

Interface element of the form

  • rear end

Create a server folder

Create a file in which index.js

The introduction of express

const express = require('express')
const app = express()

npm download and introducing cors, solve cross-domain problems (front-end and back-end is not in a domain)

app.use(require('cors')())

To solve the express recognition json submitted by the client

app.use(express.json())

npm download nodemon, when you start the back-end node need to restart the server after this every time if you do not modify the data, it will automatically detect the modifications and help you updates with nodemon

The two methods are (below)

Write only nodemon serverif the file server is up and running when, if the folder will automatically go inside to find the file index.js

nodemon server/index.js
nodemon server

Download and npm introduced mongoose

const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/element-admin', {
  useNewUrlParser: true,
  useFindAndModify: true,
  useCreateIndex: true,
  useUnifiedTopology: true
})

写数据库模型,此处只设置简单的标题和文章主体和博客对应

// 模型,习惯性用大写来表示
// 需要精确地定义每一个模型的每一个字段是什么类型的
const Article=mongoose.model('Article',new mongoose.Schema({
  title:{type:String},
  body:{type:String},
}))

npm下载并在main.js中引入axios

创建axios实例,通过定义到原型上让在所有文件中都可以访问,为了让名字不重复故加上$

Vue.prototype.$http=axios.create({
// 设置接口根地址
// 作用:就不用再所有请求中都写一遍接口根地址,比较方便
baseURL:'http://localhost:3001/api'
})
创建文章

回到server/index.js

// 新增文章的接口
app.post('/api/articles',async(req,res)=>{
  const article=await Article.create(req.body)
  res.send(article)
})

在CreateArticle.vue中,该方法绑定到<el-form>

在客户端输入信息点击对应的提交按钮后,this.$message为element的弹窗,成功则会弹出提示

同时回到index主页即文章列表

    saveArticle() {
    // 此处由于eslint判断创建的变量未使用会报错,故加上下面那行注释来解决
    this.$http.post("articles", this.article).then(res => {
      this.$message({
        message: "文章创建成功",
        type: "success"
      });
      this.$router.push('/articles/index')
    });
  }
文章列表

server/index.js

app.get('/api/articles',async(req,res)=>{
  const articles=await Article.find()
  res.send(articles)
})

ListArticle.vue

this.$http就是http://localhost:3001/api

即到后端取数据后将数据通过this.articles = res.data;传送给data里定义好的articles

created() {
  this.$http.get("articles").then(res => {
    this.articles = res.data;
  });
}
删除文章

server/index.js

删除文章成功后返回一个成功的状态

app.delete('/api/articles/:id',async(req,res)=>{
  await Article.findByIdAndDelete(req.params.id)
  res.send({
      status:true
  })
})

ListArticle.vue

先写了个fetch()方法,在删除数据之后会需要立即更新列表,故将更新的代码提出来为fetch()方法减少冗余

删除成功后同样也有个弹窗

fetch() {
this.$http.get("articles").then(res => {
  this.articles = res.data;
});
},
remove(id) {
this.$http.delete(`articles/${id}`).then(() => {
    this.$message({
      message: "文章删除成功",
      type: "success"
    });
    this.fetch()
  }
);
}

在删除按钮上绑定@click="remove(scope.row._id)",将需要删除的文章的id获取到并传输

文章详情

server/index.js

在编辑已经上传的文章的时候需要先获取到这个文章的数据将其放入输入框再进行修改

故先get到对应id文章的数据,并将数据传递过去

app.get(`/api/articles/:id`,async(req,res)=>{
  const article=await Article.findById(req.params.id)
  res.send(article)
})

EditArticle.vue

fetch(){
this.$http.get(`articles/${this.$route.params.id}`).then(res=>{
  this.article=res.data
})
}
created(){
  this.fetch()
}
修改文章

server/index.js

将修改过的数据直接用put覆盖掉原来的数据

app.put(`/api/articles/:id`,async(req,res)=>{
  const article=await Article.findByIdAndUpdate(req.params.id,req.body)
  res.send(article)
})

EditArticle.vue

同样通过id来获得对应的文章,更新成功后会有弹窗

this.$http.put(`articles/${this.$route.params.id}`,this.article).then(res => {
      this.$message({
        message: "文章更新成功",
        type: "success"
      });
      this.$router.push('/articles/index')
    });
  },

完整代码github地址:https://github.com/frotage/vue-management

 

Guess you like

Origin www.cnblogs.com/tomatofjy/p/12290689.html