发布个人文章

添加发布逻辑

1、打开 src/views/articles/Create.vue 文件,复制以下代码替换原 <script>

src/views/articles/Create.vue

 1 <script>
 2 import SimpleMDE from 'simplemde'
 3 import hljs from 'highlight.js'
 4 import ls from '@/utils/localStorage'
 5 
 6 window.hljs = hljs
 7 
 8 export default {
 9   name: 'Create',
10  // 添加相关数据
11 data() {
12   return {
13     title: '', // 文章标题
14     content: '' // 文章内容
15   }
16 },
17 mounted() {
18   const simplemde = new SimpleMDE({...})
19 
20   // 监听编辑器的 change 事件
21   simplemde.codemirror.on('change', () => {
22     // 将改变后的值赋给文章内容
23     this.content = simplemde.value()
24   })
25 
26   // 将 simplemde 添加到当前实例,以在其他地方调用
27   this.simplemde = simplemde
28   // 初始化标题和内容
29   this.fillContent()
30 },
31 methods: {
32   // 编辑器只会自动保存文章的内容,我们需要自己保存文章的标题
33   saveTitle() {
34     ls.setItem('smde_title', this.title)
35   },
36   // 初始化标题和内容
37   fillContent() {
38     const simplemde = this.simplemde
39     const title = ls.getItem('smde_title')
40 
41     // 如果 localStorage 有标题数据,使用它作为文章标题
42     if (title !== null) {
43       this.title = title
44     }
45 
46     // 使用编辑器的内容作为文章内容
47     this.content = simplemde.value()
48   },
49   // 发布
50   post() {
51     const title = this.title
52     const content = this.content
53 
54     // 如果标题和内容都不为空,提交发布
55     if (title !== '' && content.trim() !== '') {
56       const article = {
57         title,
58         content
59       }
60 
61       // 在控制台输出当前文章
62       console.log(article)
63       // 清除数据
64       this.clearData()
65     }
66   },
67   // 清除数据
68   clearData() {
69     this.title = ''
70     ls.removeItem('smde_title')
71     // 清除编辑的内容
72     this.simplemde.value('')
73     // 清除编辑器自动保存的内容
74     this.simplemde.clearAutosavedValue()
75   }
76 }
77 }
78 </script>
79 更改说明:

2、查找 <input v-validator.required,使用 v-model 绑定 title,并添加 input 事件处理器 saveTitle

1 <input v-model.trim="title" v-validator:blur.required="{ title: '标题' }" type="text" class="form-control" placeholder="请填写标题" @input="saveTitle">

3、查找 <button class="btn btn-primary",添加 click 事件处理器 post

1 <button class="btn btn-primary" type="submit" @click="post">发 布</button>

猜你喜欢

转载自www.cnblogs.com/yangguoe/p/9317483.html