全栈之巅笔记第二部分

P5:创建分类 https://www.bilibili.com/video/BV1A4411Y7fi?p=5
感谢up主,侵删

注意下面操作要装好mongodb server

(1)修改Main.vue



新建分类
分类列表
不要的可以删掉

(2)添加路由
新建CategoryEdit.vue
import CategoryEdit from '../views/CategoryEdit.vue'
再改造main.vue中el-table中间删掉加入router-view支持子路由



支持子路由还要响应修改router/index.js,加下面Children一行
const routes = [
{
path: '/',
name: 'main',
component: Main,
children:[ {path: '/categories/create',component: CategoryEdit}]
},
此时就可以跳转了

(3)CategoryEdit.vue中增加save功能
增加submit<el-form label-width="80px" @submit.native.prevent="save"> 这里指向save方法
然后export default里面添加
methods:{
save(){ } //此处尚未完成先空着
}

(4)此时需要后台数据,安装axios (Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中)
npm i axios
然后src下新建http.js,内容为:
import axios from 'axios'

const http= axios.create(
{
baseURL: 'http://localhost:3000/admin/api'
}
)
export default http

然后到main.js中引用
import http from './http'
Vue.prototype.$http = http

然后回到save加入:
this.$http.post()

(5)去server目录写接口

server/index.js
先安装express等3个包(如果没有):
npm i express@next mongoose cors

扫描二维码关注公众号,回复: 11011567 查看本文章

然后server/index.j中加入:
const express = require("express")
const app = express()
app.use(require('cors')) //引用cors和express.json模块,以支持跨域和json
app.use(express.json())
require('./plugins/db') //这里需要在server下新建plugins目录然后创建db.js
require('./routes/admin')(app)
app.listen(3000,()=>{
console.log('http://localhost:3000');
})
//db.js的内容为:module.exports = app => { //exports语法是导出一个函数

const mongoose = require("mongoose")
mongoose.connect('mongodb://127.0.0.1:27017/node-vue-moba',{
    useNewUrlParser:true
})

}

(6)再写分类路由,server下新建routes/admin/里面放后端admin路由,即在下面新建index.js:

module.exports = app => { //输出一个APP,也就是server/index.js里面引用的 require('./routes/admin')(app)
const express = require('express')
const router = express.Router()
const Category = require('../../models/Category') //注意这里引入下面(7)中的模型
router.post('/categories',async(req,res) =>{
const model = await Category.create(req.body) //必须在server/index.js中加个中间件
res.send(model)

} )
app.use('/admin/api',router) //调用app.use定义路由规则

}

(7)上面数据库、路由都弄好了,需要加入模型
在server下建立子目录models,新建Category.js,内容为
const mongoose = require('mongoose')

const schema = new mongoose.Schema({ //用Schema定义表
name:{type: String} //name字段
})

module.exports = mongoose.model('Category',schema)

(8)最后回到前端也就是前面(2)(3)步的CategoryEdit.vue来发起请求,即将save完善为
async save(){

        // const res = await this.$http.post('categories',this.model)
        this.$router.push('/categories/list')
        this.$message({
            type: 'success',
            message : '保存成功'
        })

    }

刷新看看ok了没,注意要装好mongodb server

猜你喜欢

转载自www.cnblogs.com/typh00n/p/12743964.html