[Vuejs]-Pass a variable to a child component

0👍

You have to define the bg property on your HeaderMain component:

// HeaderMain.vue

<script>
    export default {
      props: ['bg']
    }
</script>

You will then be able to use it in your template just like you did:

<header>
    <nav class="main md:bg-transparent" :class="bg"></nav>
</header>

0👍

In order to access it, you need to define props as an array inside your children component.

Look at the code below.

Vue.component('user-name', {
  props: ['name'],
  template: '<p>Hi {{ name }}</p>'
})

const LastName = {
	template: '<span> Patel </span>'
}
const Header = {
	props: ['bg'],
	template: '<span :class="bg"> {{bg}} Header </span>'
}

new Vue({
  el: "#app",
  data: function() {
    return {
      headerBg: 'header-bg'
    }
  },
  components: {
  	'last-name': LastName,
    'header-view': Header
  }
});
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

.header-bg {
  background: red;
}

.header-bg {
  background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <header-view :bg="headerBg"></header-view>
  <user-name name="Varit"></user-name>
  <last-name></last-name>
</div>

Leave a comment