iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 4
0
自我挑戰組

從0開始vue.js的30天學習日誌系列 第 4

04 Vue的模板語法 - v-text, v-html

上篇建立了一個簡單的Vue應用程式,並利用花括號{{}}將data的值綁定至DOM,除此之外也能使用v-text語法:

v-text:

<!--html-->
<div id="app01">
  <p> {{ msg }} </p>
  <p v-text="msg"></p>
</div>

<!--js-->
<script>
    new Vue({
      el: "#app01",
      data: {
        msg: "我的第一個Vue應用(ง๑ •̀_•́)ง",
      },
    });
</script>

render效果與{{}}一樣:

<div id="app01">
  <p>我的第一個Vue應用(ง๑ •̀_•́)ง</p> <!--{{}}-->
  <p>我的第一個Vue應用(ง๑ •̀_•́)ง</p> <!--v-text-->
</div>

但值得注意的是使用v-text要注意,綁定的tag如果還有別的東西,會直接被洗掉,下面的例子示範在綁v-text的tag項下塞一個span我存在 (́◉◞౪◟◉‵)

<!--html-->
<div id="app01">
  <p v-text="msg"><span>我存在 (́◉◞౪◟◉‵) </span></p>
</div>

<!--js-->
<script>
    new Vue({
      el: "#app02",
      data: {
        msg: "你走開( ͡° ͜ʖ ͡°)",
      },
    });
</script>

render結果:

<div id="app02">
  <p v-text="msg">你走開( ͡° ͜ʖ ͡°)</p>
</div>

你看(́◉◞౪◟◉‵)果不其然被趕走了/images/emoticon/emoticon02.gif


v-html:

在Vue中,不能透過{{}}v-text將html的元素插入到模板中,如果字串包含html元素會解析為字符實體,此時要使用v-html

字符實體???/images/emoticon/emoticon19.gif
例如<p>的實體字符就是&lt;p&gt;

這邊把img值設定為html元素(img tag),使用v-html綁定,另外也測試使用花括號會發生什麼事:

<!-- html -->
<div id="app03">
    <div>{{img}}</div>
    <div v-html="img"></div>
</div>

<!-- js -->
<script>
    new Vue({
      el: "#app03",
      data: {
        img: "<img src='https://i.imgur.com/iVSMcsv.png'>"
      }
    });
</script>

render結果出爐:
Imgur
˙
˙
˙

大家好我們是這樣母Tom姆熊ㄏㄏ(被揍)
上面使用{{}}是直接輸出實體字符,下面使用v-html則能成功顯示圖片。

但要注意使用v-html可能很危險,因為在讓使用者輸入時,會有機會讓他們塞入惡意script,所以如果要使用的話要特別確保資料來源是安全可靠的(比如說從自己資料庫輸入的),不要是使用者自己提供的值。

以上是v-text, v-html筆記,下一篇開始v-bind/images/emoticon/emoticon13.gif


上一篇
03 創建Vue應用程式
下一篇
05 Vue的模板語法 - v-bind屬性綁定
系列文
從0開始vue.js的30天學習日誌30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
Chimin
iT邦新手 5 級 ‧ 2018-10-19 21:06:20

/images/emoticon/emoticon37.gif

UT iT邦新手 5 級 ‧ 2018-10-20 17:12:03 檢舉

/images/emoticon/emoticon58.gif

我要留言

立即登入留言