vue的插槽----slot和自定义事件(实现点击删除本元素)

Vue 实现了一套内容分发的 API,将 元素作为承载分发内容的出口。

实例:
最终实现效果的普通代码:

<div id="app">
	<p>学习列表</p>
	<ul>
		<li>Java</li>
		<li>Linux</li>
		<li>Python</li>
	</ul>
</div>

使用slot插槽实现,并实现后边删除按钮,删除选择的目标:

<body>
<!--View层 视图-->
<div id="app">
	<father>
		<!--下面两个组件,代替的是father组件里面的slot插槽-->
		<son1 slot="fatherSon1" :titleSon="title"></son1>
		<son2 slot="fatherSon2" v-for="(itemFor.indexFor) in items"
				:itemSon="itemFor" :indexSon="indexFor" @remove="removeItems(indexFor)" :key="indexFor"></son2>
	</father>
</div>

<!--导入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<script>
	
	//slot:插槽,定义组件Vue.component("方法名",{方法体});
	//template中的\是反转义符,跟加引号是一样的效果
	//类似<div> <slot name="son1"></slot> <ul> <slot name="son2"></slot> </ul> </div>'
	Vue.component("father",{
		template:'<div>\
						<slot name="fatherSon1"></slot>\
						<ul>\
							<slot name="fatherSon2"></slot>\
						</ul>\
				</div>'
	});
	Vue.component("son1",{
		props:["titleSon"],
		template:'<div>{{titleSon}}</div>'
	});
	Vue.component("son2",{
		props:['itemSon','indexSon'],
		//绑定点击事件v-on,只能绑定组件内的点击事件(方法)
		template:'<li>{{itemSon}} <button @click="remove">删除</button></li>',
		methods:{
			remove:function(index){
				//this.$emit 自定义事件
				this.$emit('remove',index);
			}
		}
	});
	
    var vm = new Vue({
        el: "#app",
        data:{
            title:"吉吉讲课",
            items:['Jave','Linux','Python']
        },
        methods:{
        	removeItems:function(index){
        		console.log("删除了-"+this.items[index]+"-ok!");
        		this.items.splice(index,1);//当前下标,删除一个数
        	}
        }
    });
</script>

</body>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值