简体   繁体   中英

Access data variable inside a component

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?

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>

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