一、小试牛刀
真的很不好意思诸位,最近事情有点多,更新进度缓慢了,这次就简单的再复习一下vue组件的内容,大家可以自行研究一下,我就不深入解析了。
<body>
<div id="app">
<button @click="Cmop">切换组件</button>
<p></p>
<component :is="current" :name="name[current]" :color="color[current]" @change="change">
<template slot="content">
{{name[current]}}
</template>
</component>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.7.0/vue.js"></script>
<script>
Vue.component('my-component-one',{
template:`
<div>
<div style="line-height: 2.6;" :style="{background: color}">
<slot name="content"></slot>
<button @click="$emit('change',name)">回传事件</button>
</div>
</div>
`,
props:{
name:String,
color:String
}
});
Vue.component('my-component-two',{
template:`
<div>
<div style="line-height: 2.4;" :style="{background: color}">
<slot name="content"></slot>
<button @click="$emit('change',name)">回传事件</button>
</div>
</div>
`,
props:{
name:String,
color:String
}
});
new Vue({
el:'#app',
data: {
current: 'my-component-one',
name: {
'my-component-one': '我是组件一',
'my-component-two': '我是组件二'
},
color: {
'my-component-one': 'yellow',
'my-component-two': 'red'
},
},
methods: {
change(value) {
alert(value)
},
Cmop() {
if (this.current === 'my-component-one') {
this.current = 'my-component-two'
} else {
this.current = 'my-component-one'
}
}
}
})
</script>
</body>
效果
二、动手实践
<body>
<div id="app">
<!-- 组件使用者只需传递users数据即可 -->
<my-stripe-list :items="users" odd-bgcolor="#D3DCE6" even-bgcolor="#E5E9F2" @change="change">
<!-- props对象接收来自子组件slot的$index参数 -->
<template slot="cont" slot-scope="props">
<span>{{users[props.$index].id}}</span>
<span>{{users[props.$index].name}}</span>
<span>{{users[props.$index].age}}</span>
<!-- 这里可以自定[编辑][删除]按钮的链接和样式 -->
<a :href="'#edit/id='+users[props.$index].id">编辑</a>
<a :href="'#del/id='+users[props.$index].id">删除</a>
</template>
</my-stripe-list>
</div>
<script>
Vue.component('my-stripe-list', {
/*slot的$index可以传递到父组件中*/
template: `
<div>
<div v-for="(item, index) in items" style="line-height:2.2;" :style="index % 2 === 0 ? 'background:'+oddBgcolor : 'background:'+evenBgcolor">
<slot name="cont" :$index="index"></slot>
<button @click="$emit('change', item)">弹出名字和年龄</button>
</div>
</div>
`,
props: {
items: Array,
oddBgcolor: String,
evenBgcolor: String
}
});
new Vue({
el: '#app',
data: {
users: [
{id: 1, name: '张三', age: 20},
{id: 2, name: '李四', age: 22},
{id: 3, name: '王五', age: 27},
{id: 4, name: '张龙', age: 27},
{id: 5, name: '赵虎', age: 27}
]
},
methods: {
change(value) {
alert(`姓名:${value.name}, 年龄:${value.age}`)
}
}
});
</script>
</body>