Search code examples
htmlvue.jsvuejs2prev-model

Display URL entered in v-model within a HTML block


I am trying to create a code snippet builder in Vue.

When I enter a URL into a text box, I want the URL to be inserted into an HTML template, which can be copied and pasted into an HTML document. The main issue here is getting the output as raw HTML (like you would see in <pre> and <code> tags in a Medium tutorial).

Code I've tried (CodePen):

<div id="app">
  <!--myurl:{{ myUrl }}-->
  'Purchase Link <br><a href="' + myURL + '">' + myURL + "</a>"

  <child v-model="myUrl" />
</div>
const Child = {
  name: 'Child',
  template: `
    <div class="input">
      <input :value="value" @input="$emit('input', $event.target.value)">
    </div>`,
  props: {
    value: String
  }
}

new Vue({
  el: '#app',
  components: {
    Child
  },
  data () {
    return {
      myUrl: ''
    }
  }
})

Desired outcome:

<a href="https://amazon.com">amazon.com</a>

Previously using AWS SES and Node, I inserted a variable into a code block as ${myURL}. Not sure whether this approach is compatible with Vue.


Solution

  • As far as I can tell this is what you're asking for:

    const Child = {
      name: 'Child',
      template: `
        <div class="input">
          <input :value="value" @input="$emit('input', $event.target.value)">
        </div>
      `,
      props: {
        value: String
      }
    }
    
    new Vue({
      el: '#app',
      
      components: {
        Child
      },
      
      data () {
        return {
          myUrl: ''
        }
      },
      
      computed: {    
        shortUrl () {
          return this.myUrl.replace(/^https?:\/\//, '')
        }
      }
    })
    <script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
    <div id="app">
      <child v-model="myUrl"></child>
      <template v-if="myUrl">
        Purchase Link <br>
        <code>&lt;a href="{{ myUrl }}"&gt;{{ shortUrl }}&lt;/a&gt;</code>
      </template>
    </div>

    Trying to normalize URLs is pretty tricky once you start taking relative paths into account so I've kept this pretty basic. It'll just strip off the http:// or https:// from the text shown inside the tag, leaving the href exactly as typed.