学习博客:【Vue】自定义事件

自定义事件

指令作用
v-bind绑定前端界面和vue的数据 ,缩写:冒号
props绑定前端与组件的数据
v-on事件绑定 缩写:@
v-once渲染一次
v-pre跳出渲染
v-model双向绑定,用于文本框、单选、复选、下拉
v-cloak消除闪烁
this.$emit将事件从组件分发回前端界面
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<!--View层 模板-->
<div id="app">
    <phone>
        <phone-title slot="phone-title" :title="title"></phone-title>
        <phone-items slot="phone-items" v-for="(item,index) in phoneItems"
                     :item="item" v-bind:index="index" @remove="removeItems(index)" :key="index"></phone-items>
    </phone>
</div>

<!--导入Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>

<script>

    //slot插槽
    Vue.component("phone",{
        template:
            '<div>\
                <slot name="phone-title"></slot>\
                <ul>\
                    <slot name="phone-items"></slot>\
                </ul>\
            </div>'
    });

    Vue.component("phone-title",{
        props: ['title'],
        template:'<div>{{title}}</div>'
    });

    Vue.component("phone-items",{
        props: ['item','index'],
        //只能绑定当前组件方法
        template: '<li>{{item}} <button @click="remove">删除</button></li>',
        methods: {
            remove: function (index){
                //自定义事件分发 this.$emit
                this.$emit('remove',index);
            }
        }
    });

    var vm = new Vue({
        el:"#app",
        /*Model层 数据*/
        data: {
            title: "手机列表",
            phoneItems: ["诺基亚","华为","OPPO","VIVO"]
        },
        methods: {
            //此方法可被模板中自定义事件触发
            removeItems: function (index){
                console.log("已删除" + this.phoneItems[index]);
                //splice() 方法从数组中添加、删除项目并返回
                this.phoneItems.splice(index,1);
            }
        }
    });
</script>

</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值