ruby-on-railswebpackvuejs2

Pass data from Rails template to Vue Instance


I've been trying to pass data from my Rails view to the Vue component as described here

Everything works much as expected, but I'm rather stumped as to how to access the data that I'm passing in via props. Not appearing in the Vue developer tools anywhere and I'm not able to find it by fiddling with/inside the Vue object.

Could someone point me in the right direction. I'm fairly green with Vue, so struggling to even know what to search for :/

show.html.erb

<%= javascript_pack_tag 'test_vue' %>
<%= stylesheet_pack_tag 'test_vue' %>
<%= content_tag :div, id: "test", data: {
                          message: "this wont!",
                          name: "nor will this!" }.to_json do %>
<% end %>

test.vue

<template>
  <div id="app">
    <p>{{test}}{{message}}{{name}}</p>
  </div>
</template>

<script>
  export default {
    data: function () {
      return {
          test: 'This will display',
      }
    }
  }
</script>

<style>
</style>

test_vue.js

import Vue from 'vue'
import Test from './test.vue'
document.addEventListener('DOMContentLoaded', () => {
  const node = document.getElementById('test')
  const props = JSON.parse(node.getAttribute('data'))
  new Vue({
      render: h => h(Test, { props })
  }).$mount('#test');
})

Solution

  • Looks like all you need to do is declare the properties in your component:

    <template>
      <div id="app">
        <p>{{test}}{{message}}{{name}}</p>
      </div>
    </template>
    
    <script>
      export default {
        props: ["message","name"],
        data: function () {
          return {
              test: 'This will display',
          }
        }
      }
    </script>
    
    <style>
    </style>
    

    This would be the relevant documentation.

    A child component needs to explicitly declare the props it expects to receive using the props option