vue入门(四)组件基础,$emits简单用法

上一篇:vue入门(三)事件(方法)处理、侦听器、模板引用

1.组件最基础的用法:
首先有一个button.vue的组件,里面只画了一个按钮
button.vue:

<script>
export default({
    data(){
        return{
            buttonText:'button1'
        }
    },
    methods:{
        buttonClick(){
            debounce(function(){
                alert('dddd');
            },500)
        }
    }
})
</script>

<template>
    <div><button @click="buttonClick()">{{ buttonText }}</button></div>
</template>

在需要引用的vue页面里添加引用:
test.vue:

<script>
    import componets from '../form/button.vue'
    export default{
        components:{
            componets
        }
    }
</script>
<template>
    <componets/><componets/>
</template>

可以多次引用,实现的效果如下:
在这里插入图片描述
2.传入参数props:
在组件里:

export default{
	props:['title']
}

显示:

<template>
    <div><button>{{ title }}</button></div>
</template>

引用该组件时:

<componets title="传递"/><componets/>

3.父子之间调用事件($emits)
vue的例子是,在父页面调用子页面的方法,使子页面的按钮实现点击放大文字的效果
在父页面调用子页面的时候:

<template>
    <div id="div" :style="{fontSize:postFontSize+'px'}">	//这里绑定样式,可以根据数据变化改变字体大小,postFontSize为父页面data里的一个数据
        <componets title="传递" @enlarge-text="postFontSize+=1"/>	//这里把需要实现的语句放在enlarge-text事件里
        																									//这个事件的名字是子页面已经定义好的
    </div>
</template>

子页面的default export:

export default({
	emits:['enlarge-text']
})

这里相当于声明一个事件叫enlarge-text,父页面你随便调,我已经写好了。
这个事件在html里绑定到click事件,就能实现点击触发的效果了,点击后,就是父页面传给他什么语句,他就执行什么语句了。

<template>
    看我越来越大
    <button @click="$emit('enlarge-text')">Enlarge text</button>
</template>

上一篇:vue入门(三)事件(方法)处理、侦听器、模板引用

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值