Home » vue » Indexing a Vue dictionary with Laravel variable

Indexing a Vue dictionary with Laravel variable

Posted by: admin November 26, 2021 Leave a comment

Questions:

I would like to use Laravel’s double curly bracket syntax inside of Vue’s double curly bracket escaped with @ syntax.

In code below (which is not working), savingNotes is a dictionary in Vue, and I would like to use Laravel variable as a key to select an item for this dictionary.

@foreach($notes as $key => $note)
    <div class="note">
        <div class="note-heading">
            @{{ savingNotes[{{ $key }}] }}
            {{ $note->name }}
        </div>
        <hr class="note-hr">
        <div class="note-content">
            {{ $note->content }}
        </div>
    </div>
@endforeach
Answers:

You can use the @verbatim directive to escape parts that you would have transcluded by VueJS

@verbatim {{savingNotes @endverbatim ['{{$key}}'] @verbatim }} @endverbatim 

However this is code that is a head scratcher. A clearer approach would be to create a custom directive in VueJS and pass the keys to it.

new Vue({
  el: "#app",
  directives: {
    'saving-notes': {
        inserted: function (el, binding, vnode) {
            el.innerHTML = vnode.context.savingNotes[binding.expression]
        }
    }
  },
  data: {
      savingNotes: {
        'test-key': 'testvalue'
      }
  },
})

Then in your blade template, write:

    <div class="note-heading">
            <span saving-notes="{{$key}}"></span>
            {{ $note->name }}
    </div>