简体   繁体   中英

How to pass data to child component from parent vuejs

How I can pass the image url to this vue component? I'm moving the code in a separate php file that will hold the <script> tag used by Vue, but it will not recognize the passed data from a parent component.

Vue.component('theme-parallax',{
  template: '#parallax-tpl',
  data(){
    return{
      pageData: []
    }
  }
});

Component markup NB: the page.embedded.parallax_image will work correctly in the parent component. I'm new to new so To obtain the data I'm using a method in the parent component, It will be great if someone can explain me how to pass data from the main vue instance to all components.

<script type="text/x-template" id="parallax-tpl">
    <div class="row m-0">
        <div class="col-sm-12 col-md-12 col-lg-12 col-parallax p-0" v-prlx.background="{ speed: 0.08 }" :style="{ height: '70vh', backgroundImage: 'url('+page.embedded.parallax_image+')', backgroundSize: 'cover' }"></div>
    </div>
</script>

This is how I'm using the component

<script type="text/x-template" id="home-tpl">
  <div class="container-fluid p-0">

    <div class="row m-0" v-for="page in pageData">
      <div class="col-sm-12 col-md-12 col-lg-12 p-0" v-if="page.embedded.primary_featured_image">
        <img class="img-fluid w-100" :src="page.embedded.primary_featured_image">
      </div>
      <div class="col-sm-12 col-md-12 col-lg-12 p-5 mt-5">
        <h1>{{ page.title.rendered }}</h1>
      </div>
      <div class="col-sm-12 col-md-12 col-lg-12 p-5 mt-5" v-html="page.content.rendered"></div>   
    </div>

    <theme-section data-section="about" data-section-align="left"></theme-section>

    <theme-parallax v-for="page in pageData" ></theme-parallax>

    <theme-section data-section="office" data-section-align="right"></theme-section>

  </div> <!-- end container-fluid -->
</script>

You need to create a property in your component and pass the page to it from the parent.

eg parent template

<theme-parallax v-for="page in pageData" :page="page" :key="page.id"></theme-parallax>

If the page doesn't have a unique id, you should use a unique property for the key.

Then in the component

Vue.component('theme-parallax',{
  template: '#parallax-tpl',
  props: {
    page: {
      type: Object,
      default: function() {return null;},
    }
  },
  data(){
    return{
      pageData: []
    }
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM