0

I made a repository of Vue using

vue init webpack my-app

Now, my main.js is something like this --

// The Vue build version to load with the import command // (runtime-only or standalone) has been set in webpack.base.conf with an alias.

import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

Vue.component('todo-item', {
  template: '<li>{{ todo }}</li>',
  props: ['todo']
})

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App :groceryList="groceryList"/>',
  data:{
    message: 'abcdefghi',
    groceryList: [
      { id: 0, text: 'Vegetables' },
      { id: 1, text: 'Cheese' },
      { id: 2, text: 'Whatever else humans are supposed to eat' }
    ]
  }
})

My App.vue file has the template with id app as mentioned in the main.js

<template>
  <div id="app">
    At Parent: {{ groceryList[1].text }}
    <br/>
    <div>{{ message }}</div>
    <router-view/>
    <Table/>
    <Users/>

  </div>
</template>

<script>
import Users from './components/Users'
import Table from './components/Table'
export default {
  name: 'App',
  components: {
    Users,
    Table,
  },
}
</script>

Here,I keep getting errors that cannot read property groceryList and message of undefined. I have read the documentation of vue and according to it I am not making any mistakes. So, what is the problem here?

1 Answer 1

1

In main.js, you should declare data as a function and pass :message to App component

new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App :groceryList="groceryList" :message="message"/>',
  data () {
    return {
      message: 'abcdefghi',
      groceryList: [
        { id: 0, text: 'Vegetables' },
        { id: 1, text: 'Cheese' },
        { id: 2, text: 'Whatever else humans are supposed to eat' }
      ]
    }
  }
})

and in App.vue, you need to declare groceryList and message as props

<script>
import Users from './components/Users'
import Table from './components/Table'
export default {
  name: 'App',
  props: ['message', 'groceryList']
  components: {
    Users,
    Table,
  },
}
</script>
Sign up to request clarification or add additional context in comments.

4 Comments

It's one single component, why do I need to pass data as props? @ittus
They are 2 different components, one is App.vue, another is your new Vue main component
If I have to pass the same grocery list to Table component, how will it be done?
<Table :groceryList="groceryList"/>, remember to declare groceryList as prop in Table component.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.