Display URL entered in v-model within a HTML block

问题: I am trying to create a code snippet builder in VueJS. So I enter a URL in the textbox and it inserts it into the HTML code below which can be copied by the customer and...

问题:

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

So I enter a URL in the textbox and it inserts it into the HTML code below which can be copied by the customer and pasted into HTML. The main issue here is getting the output as true HTML snippet code like you would see in <pre> and <code> tags perhaps in Medium a tutorial.

CURRENT CODE and 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 I inserted a variable using NodeJS into a code block using ${myURL} - Not sure whether this approach is compatible with Vue or not.


回答1:

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/vue@2.6.10/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.


回答2:

You should use v-bind to bind data to href

<div id="app">
  Purchase Link <br><a :href="myUrl"> {{ myUrl }} </a>
  <child v-model="myUrl" />
</div>

Demo on codepen


回答3:

i created computed propety which return the html syntax and then print it on the app div

computed:{
        fixUrl(){
          return `<a href="${this.myUrl}">`
        }
      }

this is one way do do it

codepen demo

of course you can add http/s prefix if its needed

  • 发表于 2019-07-08 00:30
  • 阅读 ( 280 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除