0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

学習107日目

Posted at

テーマ

laravelでコントローラに定義した変数をjsで使う

前提

  • laravelで開発中
  • 該当部分以外は省略

内容

下記の方法がある。

bladeで埋め込む

PostsController.php

public function index()
{
    $userName = "Taro";
    return view('index', compact('userName'));
}

posts/index.blade.php

<script>
    const userName = @json($userName);
</script>

data属性を使う

PostsController.php

public function index()
{
    $userName = "Taro";
    return view('index', compact('userName'));
}

posts/index.blade.php

<div id="app" data-username="{{ $userName }}"></div>

<script>
    const app = document.getElementById('app');
    const userName = app.dataset.username;
</script>

コメント

  • railsのようにgem(gon)を使わない分シンプルだと感じた
  • api経由での取得についても調べる
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?