0
votes

Perhaps I don't understand some basic principle here, but I have been reading the documentation and trying out different approaches for 2 hours and I can't wrap my head around this.

So, I have a VueJS app, and in data I have an array named pattern. It looks something like:

[3, 4, 2, 6, 1, 8, 7, 9, 5]

In my view I am iterating through this array and showing a div for each element:

<div v-for="(ball, key) in pattern">@{{ ball }}</div>

Simple, right?

Now, I will be making the HTML inside this div more complex. But before I do that, I would like to make this a separate component (I might be reusing it elsewhere on the site so that approach seems to make sense).

So, in my main VueJS app I registered a new component:

Vue.component('rack', require('./components/Rack.vue').default);

I created Rack.vue with the following content:

<template>
    <div>
        <!-- show ball number here -->
    </div>
</template>

<script>
    export default {
        mounted() {

        }
    }
</script>

And I tried adding a <rack></rack> element to the HTML inside the for loop.

But now I have no idea how to pass the ball data to each component. I should be showing 9 rack components on the page (1 for each member of the pattern array).

I have tried adding v-model to the <rack> element but that caused a warning. I have also tried something like a :ball property but this threw an error. I take it I should be using props in some way, but I am confused by the syntax and the differences between Vue 1 and Vue 2 in this regard (I am using 2.6.10).

2
v-model is only used for input elements.Terry

2 Answers

0
votes

You can pass data to a component using props.

<template>
  <div>@{{ ball }}</div>
</template>

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

Then you would use your component in the view like this:

<template>
  <div v-for="(ball, key) in pattern" :key="key">
    <Rack :ball="ball" />
  </div>
</template>

<script>
export default {
  components: {
    Rack: () => import('./components/Rack.vue'),
  },
  data: () => ({
    pattern: [3, 4, 2, 6, 1, 8, 7, 9, 5]
  })
}
</script>
0
votes

You just need to define a prop on the rack component and then pass the value to it documentation

Vue.component('rack', {
  props: ['ball'],
  template: '<div>{{ball}}</div>'
})

new Vue({
  el: "#app",
  data() {
    return {
      pattern: [3, 4, 2, 6, 1, 8, 7, 9, 5]
    }
  },
  methods: {}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="(ball, key) in pattern">
    <rack :ball="ball"></rack>
  </div>
</div>