App.vue
<template>
<ly-product-list class="ly-u-ul">
<!-- 不写 v-slot默认就是默认插槽 -->
<template v-slot>
<ly-product v-for="(item,index) in productList" :key="index" :name="item.name" :specification="item.specification"
:price="item.price" :del="item.del" @delete="testDel">
<template v-slot:pre-icon="value">
<span v-if="value.val>0.5">🤭{{value.val}}</span>
<span v-else>😭{{value.val}}</span>
</template>
<!-- <span slot="suf-icon">😍</span> -->
</ly-product>
</template>
</ly-product-list>
</template>
<script>
import LyProductList from './components/LyProductList.vue'
import LyProduct from './components/LyProduct.vue'
export default {
name: 'App',
components: {
LyProductList,
LyProduct
},
data() {
return {
productList: [{
name: "坚果",
// 规格
specification: "1包500g",
price: 99,
del: false
},
{
name: "面包",
// 规格
specification: "1包1000g",
price: 10,
del: true
}
]
}
},
methods: {
testDel(val) {
alert(val);
}
}
}
</script>
<style>
</style>
LyProductList.vue
<template>
<ul>
<slot></slot>
</ul>
</template>
<script>
export default {
name: 'LyProductList'
}
</script>
<style>
</style>
LyProduct.vue
<template>
<li @click="testFun">
<slot name="pre-icon" :val="value" :val2="value"></slot>
{{name}}<br />
<span class="blue" v-if="!del">{{specification+price}}元</span>
<span class="blue" v-else style="text-decoration: line-through;">{{specification+price}}元</span>
<slot name="suf-icon">😂</slot>
<button v-show="del" @click.stop="currentClick">删除</button>
</li>
</template>
<script>
export default {
name: 'LyProduct',
props: {
name: {
type: String,
default: ''
},
specification: {
type: String,
default: ''
},
price: {
type: Number,
default: 0
},
del: {
type: Boolean,
default: false
}
},
data: function() {
return {
value: Math.random()
}
},
methods: {
currentClick(e) {
alert(e.target.tagName.toLowerCase());
this.$emit('delete', this.name);
},
testFun() {
alert("testFun");
}
}
}
</script>
<style scoped>
.blue {
color: blue;
}
</style>
总结:
- Vue.componet的缺陷:组件名称强制唯一、模板字符串缺乏语法高亮、遗漏了CSS、没有构建步骤。
- 若需全局定义组件,只需在main.js文件中使用Vue.compoent即可。
- Vue单文件组件中给style标签添加scoped属性后,当前文件的样式不会污染其他文件。(通过[data-v-哈希值]确保唯一性)