概述

  • 组件是一个可复用的vue实例
  • 组件通过Vue.component(组件名称, 配置)进行注册
  • 组件的data必须是返回json对象的函数,这样组件复用时每个对象都有各自的属性实例
  • 通过template定义组件的组成内容

简单Demo:

<body>
    <div id="components-demo">
        <button-counter></button-counter>
    </div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
    Vue.component('button-counter',{
        data:function(){
            return {
                count: 0
            }
        },
        template:'<button v-on:click="count++">点击了{{count}}次</button>'
    })

    new Vue({ 
        el: '#components-demo' 
    })
</script>

效果如下,每点击1次自动加1:
在这里插入图片描述

props

  • HTML页面引用的组件,可以设置各种属性值,vue组件通过 props属性接收数据
<body>
    <div id="components-demo">
        <!--如下,分别定义了title属性值-->
        <button-counter title="按钮1"></button-counter>
        <button-counter title="按钮2"></button-counter>
        <button-counter title="按钮3"></button-counter>
    </div>
</body>
Vue.component('button-counter',{
    props: ['title'],  //接收title属性
    template:'<button>{{title}}</button>'  //使用props定义的属性
})

效果:
在这里插入图片描述

props动态传值

上面的demo是通过html写死title传值,实际数据可能是动态的,把上面的例子稍作修改:

<button-counter 
	v-for="buttonText in buttonList" 
	v-bind:title="buttonText">
</button-counter>
new Vue({ 
    el: '#components-demo',
    data:{
        buttonList:['按钮1','按钮2','按钮3']
    }
})

自定义事件

  • 当我们需要在操作自定义组件后,引起组件外的元素变化,就需要用到自定义事件。即:父组件先声明事件,然后子组件操作后触发父组件事件。
  • 需求:仍然以上面的demo为例,增加个文本,显示当前点击的是哪个按钮。
<body>
    <div id="components-demo">
        <p>
            点前点击按钮:{{ buttonText }}
        </p>
        <my-button 
            v-for="button in buttonList"
            v-bind:title="button"
            v-on:show-text="buttonText=$event"></my-button>
    </div>
</body>
  • show-text:自定义事件名
  • $event:接收子组件外传的参数值,固定就是$event
<script>
    Vue.component('my-button',{
        props: ['title'],
        template: `
            <button v-on:click="$emit('show-text',title)">{{title}}</button>
        `
    })

    new Vue({ 
        el: '#components-demo',
        data:{
            buttonText: '',
            buttonList:['按钮1','按钮2','按钮3']
        }
    })
</script>
  • $emit:用来触发事件,第一个参数是触发的事件名,第二个参数是需要抛出的数据,父组件通过 $event接收
    在这里插入图片描述
posted on 2020-09-15 15:53  风停了,雨来了  阅读(269)  评论(0编辑  收藏  举报