我无法通过产品组件显示产品。
首先在我的vue.js应用程序中,我像这样通过ajax加载产品:
var app = new Vue({
el: '#app',
data: {
products: [] // will be loaded via Ajax
},
mounted: function () {
var self = this;
ajaxGetProducts(0, self); // ajax, to fetch products
},
methods: {
getProducts: function (event) {
let groupID = Number(document.getElementById("GroupSelect").value);
ajaxGetProducts(groupID, this);
}
}
});
//Ajax call to fetch Products
function ajaxGetProducts(groupID, self) {
$.ajax({
type: "POST",
url: "/Data/GetProducts",
data: { Id: groupID },
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
dataType: "json"
, success: function (response) {
self.products = response; // Loading products into the App instance
},
error: function (jqXHR, textStatus, errorThrown) {
self.products = [];
}
}).done(function () {
});
}
然后我显示这些产品,并且效果很好:
<!-- HTML -->
<div id="app">
<div v-for="prod in products" >{{prod.Id}}</div>
</div>
问题:如果我想使用组件。我怎么做? 到目前为止,这是我的组件外观:
Vue.component('product', {
props: [],
template: `<div>ProdID: {{product.Id}} {{product.Qty}}</div>`,
data() {
return {
Id: "test id"
}
}
})
示例产品对象具有以下属性:
{
Id: 1,
Qty: 5,
Title: "Nike shoes",
Price: 200,
Color: "Green"
}
最终我想像这样在HTML中使用它:
<!-- HTML -->
<div id="app">
<!-- need to pass prod object into product component -->
<div v-for="prod in products" >
<product></product>
</div>
</div>
我知道我必须以某种方式通过Component属性传递对象吗? 将每个属性1传递1并不是一个好主意,因为此产品可能会更改,因此属性名称可以更改或添加更多。我认为应该有一种方法可以将整个Product对象传递给Product组件,对吧?
答案 0 :(得分:4)
您可以通过props
类似的东西
Vue.component('product', {
props: ['item'],
template: `<div>ProdID: {{item.Id}} {{item.Qty}}</div>`
})
并像这样传递它;
<div id="app">
<div v-for="prod in products" :key='prod.Id'>
<product :item='prod'></product>
</div>
</div>
答案 1 :(得分:1)
如何将其作为
<product v-for="prod in products" :key="prod.Id" :product="prod"></product>
并在组件中:props: {product:{type: Object, required: true}}
?
然后在组件模板中可以使用{{product.Id}}