Search code examples
javascriptvue.jsvariablesvuejs3

How to add variables in vue and use them as a code editor?


I am building a code editor in vue, which has 4 main parts: the html-code, the css-code, the js-code and the result (preview). I want to add variables from the data (html code, css code and js code) so I can use the added data for the result in the code editor.

My template looks like this:

<template>
  <div class="grid">
    <div id="html" class="grid-cell">
      <textarea v-model="htmlCode" name="" id="" cols="30" rows="10"></textarea>
      <div class="title">This is a cell</div>
    </div>
    <div id="css" class="grid-cell">
      <textarea v-model="cssCode" name="" id="" cols="30" rows="10"></textarea>
      <div class="title">This is a cell</div>
    </div>
    <div id="js" class="grid-cell">
      <textarea v-model="jsCode" name="" id="" cols="30" rows="10"></textarea>
      <div class="title">This is a cell</div>
    </div>
    <div id="preview" class="grid-cell">
      <div v-html="htmlandcss"></div>
      <div class="title">This is a cell</div>
    </div>
  </div>
</template>

And my script looks like this:

<script>
export default {
  name: "CodeEditor",
  methods: {},
  data() {
    return {
      htmlCode: '<h1>hi</h1>',
      cssCode: '',
      jsCode: '',
      htmlandcss: this.htmlCode + this.cssCode
    }
  },[![this is ][1]][1]
  computed: {
  }
};
</script>

My result in the code editor itself should look like an h1.

This is my result for now:

https://i.sstatic.net/J25qW.png


Solution

  • Make your result-variable a computed property and the problem is gone:

    <script>
    export default {
      name: "CodeEditor",
      methods: {},
      data() {
        return {
          htmlCode: '<h1>hi</h1>',
          cssCode: '',
          jsCode: '',
        }
      },
      computed: {
        htmlandcss() {
          return this.htmlCode.concat(this.cssCode);
      }
    };
    </script>