我在创建组件/模板时遇到问题。我几乎按照这里的说明进行操作:
https://www.vuemastery.com/courses/intro-to-vue-js/components
我的代码与视频中的代码基本相同(当然错误除外)
我的问题是,该组件根本没有显示。
这是我完整的Vue.JS代码:
Vue.config.devtools = true;
var app = new Vue({
delimiters: ['[[', ']]'],
el: '#app',
});
Vue.component('product', {
template:
`<div class='product'>
<button class="btn btn-outline-success my-2 my-sm-0">Items [[ cart ]]</button>
<div class="row">
<div class="col-md">
<img :src=image class="rounded float-left" alt="..." style="width: 50%">
</div>
<div class="col-md">
<h1>Products: [[ title ]]</h1>
<p>Description: [[ description ]]</p>
<p v-if="inStock">In Stock</p>
<p v-else :class="{outOfStock: inStock == 0}">Out of stock</p>
<ul v-for="detail in details">
<li>[[ detail ]]</li>
</ul>
<div v-for="(variant, index) in variants"
:key="variant.variantId"
class="color-box"
@mouseover="updateProduct(variant.variantImage, index)"
:style="{ backgroundColor: variant.variantColor }">
</div>
<br>
<button @click="addToCart"
:disabled="!inStock">
Add to Cart
</button>
</div>
</div>
</div>`,
data() {
return {
product: 'Essen ',
brand: "Muhannad Kalieh",
description: 'Thats my description for the socks',
selectedVariant: 0,
onSale: true,
details: ["Selber zubereitet", "frische Zutaten", "schmeckt geil nahuj"],
variants: [
{
variantId: 2224,
variantColor: "green",
variantQuantity: 15,
variantImage: '/images/essen1.jpeg',
sale: 1
},
{
variantId: 34,
variantColor: "blue",
variantQuantity: 0,
variantImage: '/images/essen2.jpeg',
sale: 0
}
],
cart: 0
}
},
methods: {
addToCart() {
this.cart += 1
},
updateProduct(variantImage, index) {
this.selectedVariant = index;
}
},
computed: {
title() {
return this.brand + ' ' + this.product;
},
image() {
return this.variants[this.selectedVariant].variantImage;
},
inStock() {
return this.variants[this.selectedVariant].variantQuantity;
}
}
});
和HTML
<div id="app">
<product></product>
</div>
在我尝试将代码用作组件之前,所有代码都有效。也许是因为分界线?还是反叛``?我真的不再有任何线索了
感谢您的帮助!
答案 0 :(得分:2)
您必须在vue实例上声明您的组件。在Vue.js模板中,您需要将自定义模板封装在其他<div></div>
内。它会是这样的:
// your template
Vue.component('product', {
template:
`
<div>
<div class='product'>
... your vue codes here
</div>
</div>
`
});
Vue.config.devtools = true;
var app = new Vue({
delimiters: ['[[', ']]'],
el: '#app'
});
答案 1 :(得分:1)
在实例化新的Vue实例之前,需要声明组件。 此外,要使分隔符起作用,您需要将它们放在组件声明中。
您可以看到一个有效的示例here
Vue.component('product', {
delimiters: ['[[', ']]'],
template:....
});
var app = new Vue({
el: "#app",
});