我已经阅读了很多文档和教程,但我仍然不明白我做错了什么。我曾多次尝试重建这个简单的组件,但没有成功。我收到以下错误:
[Vue warn]: Error in data(): "ReferenceError: products is not defined"
found in
---> <Products> at resources/assets/js/components/Products.vue
<Root>
app.js:19613:7
ReferenceError: products is not defined
[Vue warn]: Property or method "data" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
found in
---> <Products> at resources/assets/js/components/Products.vue
<Root>
app.js:19613:7
[Vue warn]: Error in render: "TypeError: _vm.data is undefined"
found in
---> <Products> at resources/assets/js/components/Products.vue
<Root>
这是我的 app.js
文件:
window.Vue = require('vue');
/**
* Next, we will create a fresh Vue application instance and attach it to
* the page. Then, you may begin adding components to this application
* or customize the JavaScript scaffolding to fit your unique needs.
*/
Vue.component('products', require('./components/Products.vue'));
const app = new Vue({
el: '.main-container',
data: {
products: []
}
});
这是Products.vue
:
<template>
<div class="row">
<div class="columns large-3 medium-6" v-for="product in data.products" :key="product.product_key">
<div class="card">
<div class="card-divider">
@{{ product.title }}
</div>
<a :href="product.product_key" target="_blank"><img :src="product.image"></a>
<div class="card-section">
<p>@{{ product.product_description }}</p>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data: function () {
return products
},
mounted () {
this.getProducts();
},
methods: {
getProducts() {
axios.get('/products/').then((response) => {
this.products = response.data.results;
}).catch( error => { console.log(error); });
}
}
}
</script>
我知道我可能将 .vue
文件与我试图在 app.js
中设置的一些属性混淆了——任何人都可以直接告诉我吗如何访问数据?
最佳答案
将 Products.vue
更改为:
data: function () {
return products
},
至
data() {
return {
products: [],
}
}
当 data() 对象位于 Vue 根对象中或位于组件中时,设置 data() 对象是有区别的。
就您而言,您不应将返回产品
放入app.js
中。 products
对象将存在于该 Products.vue
组件中,并且可以通过 this.products
访问。
关于javascript - Laravel 5.5 和 Vue.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48758124/