Skip to content

Instantly share code, notes, and snippets.

@flxxyz flxxyz/App.vue
Last active Aug 26, 2019

Embed
What would you like to do?
Vue注册全局指令,实现在标签上编码markdown
<template>
<div id="app">
<Test/>
</div>
</template>
<script>
import Test from './Test'
export default {
name: 'App',
components: {
Test,
},
}
</script>
import Vue from 'vue'
import App from './App'
import markdown from './markdown';
Vue.config.productionTip = false
//注入markdown解析器
Vue.use(markdown.install)
Vue.prototype.$marked = markdown.marked
new Vue({
render: h => h(App)
}).$mount('#app')
/**
* 自定义的markdown实现
* 这里实现了两种方法,直接是用钩子绑定到vue的指令
* 还有一种是挂载到原型链上操作
*/
import marked from 'marked'
import('highlight.js/styles/atom-one-dark.css')
marked.setOptions({
renderer: new marked.Renderer(),
pedantic: false,
gfm: true,
tables: true,
breaks: false,
sanitize: false,
smartLists: true,
smartypants: false,
xhtml: false,
highlight(code) {
return require('highlight.js').highlightAuto(code).value;
},
})
let install = (Vue) => {
if (install.installed) return;
Vue.directive('markdown', {
bind: (el, binding, vnode) => {
el.innerHTML = marked(binding.value)
},
update: (el, binding, vnode) => {
el.innerHTML = marked(binding.value)
}
})
}
export default {
marked,
install,
}
{
"dependencies": {
"highlight.js": "^9.15.6",
"marked": "^0.6.1",
"vue": "^2.5.22"
}
}
<template>
<div>
<div v-if="isNotFound">404</div>
<div v-else v-markdown="article"></div>
</div>
</template>
<script>
const 这是一个查找文章的接口 = function () {
return new Promise((resolve, reject) => {resolve(id)})
}
export default {
name: "Test",
data() {
return {
article: '',
isNotFound: true,
}
},
methods: {
handlerArticle(id) {
//查找本地文章
let a = this.findArticle(id, async (id) => {
return await 这是一个查找文章的接口(id);
})
if (a == null) {
return 404;
}
return a;
},
findArticle(id, callback) {
// let res = '## Test';
let res = null;
if (res === null) {
return callback(id);
}
return res;
}
},
mounted() {
//用id来查找文章
let a = this.handlerArticle(123);
if (a === 404) {
//跳到错误页面
}
//处理loading
this.isNotFound = false;
this.article = a; //将markdown内容直接保存到变量
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.