技術棧:vue+element+express+mongodb
教程:b站“全棧之巔”
github地址:https://github.com/frotage/vue-management
前言:本人平常寫的是前端,這次主要是想學習一下express,而前端界面的實現主要都是用了element直接調用,就沒有寫的特別詳細
具體:
-
mongodb安裝
官網下載安裝完畢后,設置data的地址,沒有再去設置后台自動啟動,選擇開兩個cmd
兩個cmd模式的開啟方式:
先開一個cmd
mongod --dbpath D:\mongodb\data\db
再開一個cmd
mongo
over
-
前端vue-cli創建項目
vue create 項目名稱
選擇的時候把router加上創建
vue add element
選擇的時候選擇全局安裝,就不用后期用一個再注冊一個
主界面App.vue用element-ui里的container搭建
側邊欄留兩個
把文件夾views原來的刪掉,新建文件
CreateArticle.vue =>新建文章
EditArticle.vue =>編輯文章
ListArticle.vue =>文章列表
把App.vue的兩個鍵index調整為:
<el-menu-item index="/articles/create">新建文章</el-menu-item>
<el-menu-item index="/articles/index">文章列表</el-menu-item>
打開router里面的index.js
將剛剛在views里面創建的三個vue引入
為三個vue設置對應的路由
//剛打開網頁的時候引向文章列表
{
path: '/',
name: 'Home',
redirect:'/articles/index'
},
//文章列表
{
path:'/articles/index',
name:'list-article',
component:ListArticle
},
//創建文章
{
path: '/articles/create',
name: 'create-article',
component:CreateArticle
},
//根據文章自動生成的id來編輯文章
{
path:'/articles/:id/edit',
name:'edit-article',
component:EditArticle
}
CreateArticle.vue
用element的form
在<el-form>上設置方法用於post輸入的信息給后端
@submit.native.prevent="saveArticle"
在<el-form>上綁定:model="article"
再在文章標題和文章內容對應的<el-input>上分別加上
v-model="article.title"
v-model="article.body"
在data中創建article:{}
ListArticle.vue
用element的table
在<el-table>里面加上:data="articles"
EditArticle.vue
界面為element的form
-
后端
創建server文件夾
在其中創建index.js文件
引入express
const express = require('express')
const app = express()
npm下載並引入cors,解決跨域問題(后端和前端不在一個域)
app.use(require('cors')())
解決express要識別客戶端提交的json
app.use(express.json())
npm下載nodemon,在啟動后端node時如果不用這個則每次修改完數據之后需要重新啟動服務器,用nodemon則會自動檢測修改並幫你更新
兩種啟動方式都可以(如下)
在只寫nodemon server
時如果server是文件則啟動運行,倘若是文件夾則會去自動找里面的index.js文件
nodemon server/index.js
nodemon server
npm下載並引入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