2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Vue.js で SSR の props を boolean で渡す際に json_encode が便利かも

2
Posted at

Vue.js で SSR の props を boolean で渡す際に json_encode が便利かも

というか サーバサイドから渡す際には基本的に JSON 形式で (json_encode の結果として) 渡したほうがよいかもという話になります。

サーバサイドレンダリングからの props 指定の方法

Laravel のドキュメントに記載されているように サーバサイドレンダリングからの出力を
Vue.js での props に渡すような方法
は広く知られていることでしょう。

The @json directive is also useful for seeding Vue components or data-* attributes:

<example-component :some-prop='@json($array)'></example-component>

slot 経由などという余計な手段をとる必要などはあんまりありません。

Boolean 単品を props として渡したい

前述の事例では配列を JSON 化して props に渡していました。
では Boolean などはどのようにしたらよいでしょう?

答えは・・・

<example-component :some-bool='@json($bool)'></example-component>

$array の代わりに $bool を渡しました。
$bool は PHP の出力において Boolean 型を想定するものです。

これは正しいのでしょうか?
以下の記述にて試してみると

test.php
var_dump(
	json_encode(true),
	json_encode(false)
);
$ php test.php
string(4) "true"
string(5) "false"

出力としては true, false それぞれの文字列としての出力が行われました。
これがサーバサイドからのレンダリングであれば JavaScript の true, false に合致します。
処理の結果としては正しく見えますが・・・

JSON の RFC について

上記の事例が PHP の出力として間違っていないかを確認するためにマニュアルを見てみると
PHP:json_encode - Manual では

注意:

PHP の実装は、 » RFC 7159 の JSON のスーパーセットです

そして RFC 7159 の 3. Values にて

A JSON value MUST be an object, array, number, or string, or one of the following three literal names:

  false null true

JSON の値は オブジェクト, 配列, 数値, 文字列 あるいは以下三つのうちのいずれか
false, null, true

と記載されているようです。

これは PHP の json_encode() の引数として指定可能であるのは上記の事例の型であり
true, false が文字列化するのは JSON としての Boolean として適切な記述に変換されている・・・と思われます。

PHP 単に Boolean を出力すると空白などになってしまうようですからね・・・

2
1
0

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?