欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Vue中插入HTML代码的方法

程序员文章站 2023-11-19 12:44:04
我们需要吧

hello world

插入到

my name is pjee

应该如何做? 一、使用v-...

我们需要吧<p>hello world</p>插入到<p>my name is pjee</p>应该如何做?

一、使用v-html

v-html:更新元素的 innerhtml

const text = `<p>hello world</>`
<p>
  my name is pjee
  <p v-html='text'></p>
</p>

注意:你的站点上动态渲染的任意 html 可能会非常危险,因为它很容易导致 xss 攻击。请只对可信内容使用 html 插值,绝不要对用户提供的内容使用插值。

二、渲染函数

渲染函数:这是通过对vnode(虚拟dom)的操作来生成

text(){
  render:(h)=>{
   h(
     'div', 
     [
      h('p', 'hello'),
      ' world!'
     ]
    )
  }
}
<p>hello world{{this.text()}}</p>

三、jsx

jsx:这个方法在react使用最为广泛,但是vue中使用需要安装babel插件

text(){
  return (<p>hello world</p>)
}
<p>hello world{{this.text()}}</p>

四、dompropsinnerhtml

dompropsinnerhtml:如果说jsx在vue很少用到,那么这个东西就更少有人使用到了

如果现在还有一段<p>how are you?</p>需要我们插入到hello world中,我们就可以使用这种方法

const newtext = '<p>how are you?</p>'
text(){
 return (
  <p>
   hello world
   <p dompropsinnerhtml={this.newtext}></p>
  </p>
 )
}
<p>hello world{{this.text()}}</p>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。