淺入深出Vue:文章編輯


登錄與注冊功能都已經實現,現在是時候來開發文章編輯功能了。

這里咱們就使用 markdown 作為編輯語言吧,簡潔通用。那么我們就需要找一下 markdown 的編輯器組件了,而且還要支持 vue噢。

若羽這里找到的一個是 mavonEditor,在 github 上有2k+ 的 star。文檔也都是中文的,比較友好。

mavonEditor地址

添加組件 && 新建編輯組件

首先來安裝一下編輯器:

npm install mavon-editor --save

然后在 main.js 中引入組件:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import mavonEditor from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'

Vue.config.productionTip = false
Vue.use(ElementUI)
Vue.use(mavonEditor)

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

接下來新建我們的編輯組件了,Edit.vue:

<template>
    <div></div>
</template>

<script>
    export default {
        name: "Edit"
    }
</script>

<style scoped>

</style>

然后為它添加路由對象:

{
    path: '/edit',
    name: 'edit',
    component: () => import('./views/Edit.vue')
}

編寫視圖代碼

首先一篇文章有哪些要素

  • 標題
  • 內容

最基本是需要這兩個要素的。

data 中定義這兩個要素:

data() {
    return {
        model: {
            title: '',
            content: '',
        }
    }
}

在布局上我們依舊延續之前的簡約風,使用 ElementUI 進行布局。但這里我們不居中了,直接填滿全屏就好。

代碼:

<template>
    <div>
        <el-row>
            <el-form>
                <el-form-item label="文章標題">
                    <el-col :span="6">
                        <el-input v-model="model.title"></el-input>
                    </el-col>
                </el-form-item>

                <el-form-item>
                    <el-col>
                        <mavon-editor v-model="model.content"></mavon-editor>
                    </el-col>
                </el-form-item>

                <el-form-item>
                    <el-col>
                        <el-button type="primary" size="small" @click="submit">發表</el-button>
                    </el-col>
                </el-form-item>
            </el-form>
        </el-row>
    </div>
</template>

<script>
    import axios from 'axios'
    export default {
        name: "Edit",
        data() {
            return {
                model: {
                    title: '',
                    content: '',
                }
            }
        },
        methods: {
            submit() {
                 axios.post('https://451ece6c-f618-436b-b4a2-517c6b2da400.mock.pstmn.io/publish', this.model)
                     .then(res => {
                         if(res.data.Code === 200) {
                             this.$message.success('發布成功');
                         }
                     })
            }
        }
    }
</script>

效果如下:

寫在后面

這個頁面也還確實了一部分功能,在發布完成后,應該是要跳轉到文章列表的頁面去查看所有的文章。

因為列表頁面還沒有做,所以這里暫時先挖個坑放着~

本篇博文使用了第三方組件,也是在演示如何使用第三方組件來為自己提高開發效率,畢竟不可能所有的東西都自己來從0實現,那多累,還不一定能保證完善。部分第三方組件無法滿足的功能就可以考慮自己來實現了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM