Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data to single file components in Vue.js?

I have a single file component header.vue:

<template>
  <h1>{{text}}</h1>
</template>

<script>
  export default {
    data() {
      return {
        text: 'Header text',
      };
    },
  };
</script>

I require it in my code as follows

const Header = require('components/header.vue');

And call it:

const header = new Vue({
  el: '#header',
  data: {
    text: 'New header text',
  },
  render: h => h(Header),
});

The component is rendered, but the text says Header text instead of New header text. Why?

like image 536
Mikko Avatar asked Nov 30 '16 11:11

Mikko


2 Answers

You have two separate components here, the Header component and the anonymous component you created (with new Vue()). The anonymous component renders the Header component as its child. Both components have separate data properties; the parent has text = 'New header text' and the child has text = 'Header text'.

There are two ways (off the top of my head) that you can achieve this:

  1. Extend the Header component and override its text data property with the new value:
const Header = require('components/header.vue');
const HeaderComp = Vue.extend(Header);

const header = new HeaderComp({
  el: '#header',
  data: {
    text: 'New header text',
  },
});
  1. By making text a prop instead, you will be able to pass data down to the child from the parent:

header.vue

<script>
  export default {
    props: ['text'],
  };
</script>

usage

const Header = require('components/header.vue');

// Using render function

const header = new Vue({
  el: '#header',
  render: h => h(Header, {
    props: {
      text: 'New header text',
    },
  }),
});

// Using template

const header = new Vue({
  el: '#header',
  components: {
    Header,
  },
  template: '<header text="New header text"/>',
});
like image 86
Decade Moon Avatar answered Oct 03 '22 10:10

Decade Moon


I think there can be two ways to solve this:

  1. you can pass the header as props

To pass props you have to make following changes in header.vue:

<script>
  export default {
    props: ['text'],
  };
</script>

And call it:

const header = new Vue({
  template: '<header :text="text" />',
  data: {
    text: 'New header text',
  }
}); 
  1. You can have header as a vuex variable and use it in the header component.
like image 35
Saurabh Avatar answered Oct 03 '22 10:10

Saurabh