UNPKG

2.22 kBJavaScriptView Raw
1import editor from 'vue2-ace-editor'
2import _ from 'underscore'
3
4export default {
5 template: `
6 <div ref="wrapperBox">
7 <component :is="userComponent"></component>
8 <p class="bd__button"><a href="#" @click.prevent="toggleEditor">Modify Example Code</a></p>
9 <div style="margin-bottom: 20px" v-show="isActive">
10 <editor
11 v-model="code"
12 @init="editorInit"
13 lang="jsx"
14 theme="monokai"
15 width="100%"
16 height="200"
17 mode="jsx">
18 </editor>
19 </div>
20 </div>
21 `,
22 props: {
23 defaultCode: String
24 },
25 data: function () {
26 return {
27 code: this.defaultCode,
28 userComponent: this.renderComponent(this.defaultCode),
29 isActive: false,
30 }
31 },
32 components: {editor},
33 created: function () {
34 this.debounceRenderComponent = _.debounce(this.renderComponent, 500).bind(this)
35 },
36 methods: {
37 toggleEditor: function () {
38 this.isActive = !this.isActive
39 },
40 editorInit: function () {
41 require('brace/ext/language_tools') //language extension prerequsite...
42 require('brace/mode/jsx') //language
43 require('brace/theme/monokai')
44 },
45 renderComponent: function (originalCode) {
46 const code = originalCode || this.code
47 let json = {}
48 try {
49 if (code && code.length && code[0] === '{') {
50 json = eval('(' + code + ')')
51 }
52 } catch(e) {
53 // simply example is not a json object
54 }
55
56 try {
57 json.components = vueComponents
58 json.template = json.template || code
59 const component = Vue.component('user-component', json)
60 this.userComponent = component
61 return component
62 } catch (error) {
63 console.log(error)
64 }
65 }
66 },
67 updated: function () {
68 this.$nextTick(function () {
69 window.updateHeight(this.$refs.wrapperBox.clientHeight)
70 })
71 },
72 mounted: function () {
73 this.$nextTick(function () {
74 window.updateHeight(this.$refs.wrapperBox.clientHeight)
75 })
76 },
77 watch: {
78 // whenever question changes, this function will run
79 code: function (newCode, oldCode) {
80 this.debounceRenderComponent(newCode)
81 }
82 },
83}
\No newline at end of file