LoginSignup
101
69

More than 5 years have passed since last update.

Vue2.0とnl2br

Last updated at Posted at 2016-10-15

vue2.0ではv-htmlに対してfilterが使えなくなりました。
これまで改行含むテキストに対して<p v-html="message | nl2br"></p>とやっていたものを、
どう修正するか試したメモです。

v-htmlとreplace

デモ

html
<p v-html="message.replace(/\n/g,'<br/>')"></p>

メリット : わかりやすい。
デメリット : エスケープされない。

v-forとsplit

デモ

html
  <div v-for="str of message.split('\n')">{{str}}</div>

メリット : エスケープされる。
デメリット : 改行が続くと空のdivが出たりと、出力されるhtmlが微妙。

関数型コンポーネント

デモ

html
  <nl2br tag="p" :text="message"></nl2br>
js
Vue.component('nl2br', {
  functional: true,
  props: ['tag','text'],
  render: function (createElement, context) {
    return createElement(context.props.tag,
      context.props.text.split("\n").reduce(function(x,y){
          if (!Array.isArray(x)){
            return [x,createElement('br'),y];
          }
          return x.concat([createElement('br'),y]);
      }));
  }
});

メリット : エスケープされる。renderが使えて少し楽しい。
デメリット : renderめんどい

css

デモ

html
<p style="white-space: pre;" v-text="message"></p>

(折り返す時はwhite-space: pre-wrap;などを使う)

メリット : 楽。エスケープされる。
デメリット : ない。

まとめ

cssでいいのか……? cssでいいな……。

101
69
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
101
69