Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS Passing data Through render

I'm currently working with VueJS 2, I would like to pass some params from the HTML to the VueJS component. Let me show you.

My Html Div looks like this :

<div id="app" :id="1"></div>

And my javascript :

new Vue({
  store, // inject store to all children
  el: '#app',
  render: h => h(App)
});

My App Component:

<template>
  <div>
    {{ id }}
  </div>
</template>
<script>
export default {
  props: {
   id: Number
  }
}
</script>

I would like to get the id passed in the Html, in my App component. How should I do ?

like image 285
Alexis Darnat Avatar asked Mar 16 '17 20:03

Alexis Darnat


People also ask

How do I pass my value to component Vue?

Using Props To Share Data From Parent To Child # VueJS props are the simplest way to share data between components. Props are custom attributes that we can give to a component. Then, in our template, we can give those attributes values and — BAM — we're passing data from a parent to a child component!

How do I transfer data to Vue props?

The way it works is that you define your data on the parent component and give it a value, then you go to the child component that needs that data and pass the value to a prop attribute so the data becomes a property in the child component. You can use the root component (App.


1 Answers

Here is one way.

<div id="app" data-initial-value="125"></div>

new Vue({
  el: '#app',
  render: h => h(App, {
    props:{
      id: document.querySelector("#app").dataset.initialValue
    }
  })
})

But you don't have to use a render function.

new Vue({
  el: '#app',
  template:"<app :id='id'></app>",
  data:{
    id: document.querySelector("#app").dataset.initialValue
  },
  components:{
    App
  }
})

Also, I'm using querySelector assuming you rendered initialValue (instead of id) to the page as an attribute, but you could just as easily put it somewhere else on the page like a hidden input or something. Really doesn't matter.

like image 116
Bert Avatar answered Oct 10 '22 19:10

Bert