[英]Access data variable inside a component
我使用创建了Vue的存储库
Vue初始化Webpack我的应用
现在,我的main.js
就是这样-
//使用import
命令加载的Vue构建版本//(仅运行时或独立运行)已在webpack.base.conf中设置为别名。
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' }
]
}
})
我的App.vue
文件具有App.vue
中提到的ID为app
的模板
<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>
在这里,我不断收到cannot read property groceryList and message of undefined
错误。 我已经阅读了vue的文档,据此我没有犯任何错误。 那么,这是什么问题呢?
在main.js
,您应该将data
声明为一个函数,并将:message
给App组件
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' }
]
}
}
})
在App.vue
,您需要将groceryList
和message
声明为props
<script>
import Users from './components/Users'
import Table from './components/Table'
export default {
name: 'App',
props: ['message', 'groceryList']
components: {
Users,
Table,
},
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.