vue使用markedjs的demo

3,578 阅读1分钟

vue与markedjs

  1. 引入marked以及highlight.js

    npm i -S marked
    npm i -S highlight.js
    
  2. 在main.js中引入highlight的css样式【这里样式可以自己选取

    import 'highlight.js/styles/idea.css'
    
  3. 组件使用

      <div class="write">
          <textarea
            name="article"
            v-model="article"
          ></textarea>
        </div>
      <div class="show" v-html="showArticle"></div>
    
    import { marked } from 'marked'
    import hljs from 'highlight.js'
    export default{
        name:'component',
        data(){
            return{
                article: '',
                showArticle: ''
            }
        },
        mounted(){
            marked.setOptions({
            renderer: new marked.Renderer(),
            highlight: function (code, lang) {
                const language = hljs.getLanguage(lang) ? lang : 'plaintext'
                return hljs.highlight(code, { language }).value
            },
            langPrefix: 'hljs language-',
            pedantic: false,
            gfm: true,
            breaks: false,
            sanitize: false,
            smartLists: true,
            smartypants: false,
            xhtml: false
            })
        },
        watch:{
            article (newVal) {
            this.showArticle = marked.parse(newVal)
            }
        }
    }
    

image.png