Components inside components

Now that we know how to write Single-File Components, we want to use them inside other components to compose the interface of the app.

To use a component inside another component, we need to import it and expose it to the template:

  1. First, create a new component. For example, here's a Movie.vue component:
      <template>
<li class="movie">
{{ movie.title }}
</li>
</template>

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

<style scoped>
.movie:not(:last-child) {
padding-bottom: 6px;
margin-bottom: 6px;
border-bottom: solid 1px rgba(0, 0, 0, .1);
}
</style>

We will also need a Movies.vue component if you haven't created it already. It should look like this:

<template>
<ul class="movies">
<li v-for="movie of movies" class="movie">
{{ movie.title }}
</li>
</ul>
</template>

<script>
export default {
data () {
return {
movies: [
{ id: 0, title: 'Star Wars' },
{ id: 1, title: 'Blade Runner' },
],
}
},
}
</script>
  1. Then, import the Movie SFC in the script of the Movies component:
      <script>
import Movie from './Movie.vue'

export default {
// ...
}
</script>
  1. Set the components option to expose some components to the template, with an object (the key is the name that we will use in the template, and the value is the component definition):
      export default {
components: {
Movie,
// Equivalent to `Movie: Movie,`
},

// ...
}
  1. We can now use the component with the Movie tag in the template:
      <template>
<ul class="movies">
<Movie v-for="movie of movies"
:key="movie.id"
:movie="movie" />
</ul>
</template>

If you are using JSX, you don't need the components option, as you can use a component definition directly if it starts with a capital letter:

import Movies from './Movies.vue'

export default {
render (h) {
return <Movies/>
// no need to register Movies via components option
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.100.34