vue组件

作者: 阿昕_ | 来源:发表于2018-07-02 03:05 被阅读48次

组件

<tmp></tmp>
  • 组件是可复用的 Vue 实例,且带有一个名字
  • 组件中data是一个函数,返回一个json

全局组件

  • Vue.component()
  • Vue.component('组件名称',{})
  • 全局可用
Vue.component('tmp',{
    template:`<div @click='run'>{{str}}</div>`,
    data(){
        return {
            str:'这是一个组件'
        }
    },
    methods:{
        run(){
            console.log(1)
        }
    }
})

局部组件

  • 挂载到实例的components属性上
  • components(组件名称,{})
  • 只能在对应实例下使用
new Vue({
    el:'#app',
    data:{
        msg:'hello'
    },
    components:{
        subtmp:{
            template:`<div @click='run'>{{str}}</div>`,
            data(){
                return {
                    str:'这是一个局部组件'
                }
            },
            methods:{
                run(){
                    console.log(2)
                }
            }
        }
    }
})

父==》子 自定义属性props信息传递

  • 组件设置自定义属性 : props:["msg"]
  • html内组件设置此属性的值::pmsg='msg'
  • 组件内部即可使用:{{msg}}

子==》父 自定义事件$emit()

  • this.$emit('myevent',mydata)
  • this.$on('myevent',(data)=>{})

props验证

props:{
    msg:{
        type:Number, //String,Number,Function,Object,Boolean,Array
        default:10,
        required:true,
        
        validator:(value)=>{
            return value>10;
        }
    }
}

slot分发

<a>
    <!-- 当写在自定义标签之间的内容 要混合子组件中的模板 -->
    <div slot="one">替换第1个</div>

    <div slot="three">替换第3个</div>
    
    <template slot="two">
        <div>替换第2个</div>
        <div>替换第2个</div>
        <div>替换第2个</div>
        <div>替换第2个</div>
        <div>替换第2个</div>
        <div>替换第2个</div>
    </template>

    <div>替换无名的slot</div>
    
</a>
 Vue.component("a",{
    template:`
        <div>
            <slot name="one"><p>这是第1个</p></slot>
            <slot name="two"><p>这是第2个</p></slot>
            <slot name="three"><p>这是第3个</p></slot>

            <slot>无名的slot</slot>    
            
        </div>
    `
})

相关文章

网友评论

      本文标题:vue组件

      本文链接:https://www.haomeiwen.com/subject/dnckuftx.html