slot分发内容

一、slot定义

中文插槽混合父组件的内容与子组件自已模板的方式
其中 Vuejs 把 slot 元素作为原始内容的插槽

二、编译作用域

//父组件
{{msg}}
//msg绑定到是父组件的内容 //子组件 ... components:{ 'my-component':{ template:'
' } } ...

小总结:
父组件模板内容在父组件作用域内编译
子组件模板内容在子组件作用域内编译

三、slot用法

1、单个插槽

//html
...
我是父组件内容

//js
...
template:'
\ \ 如果没有内容显示,默认是我\ \
' ...

2、具名插槽

//html
...
具名插槽(有具体名字的插槽): 视图不变,数据变

  

我是标题

我是正文内容

正文内容有两段

我是底部信息

//js ... 'name-component':{ template:'
\
\n' + ' ' + //取出name是 header 对应的内容 '\n' + '
\n' + ' \n' + '
\n' + ' ' + // 没加 name 会把默认的取回来 '\n' + '
\n' + '\n' + ' ' + '
' } }

【Demo实例https://jsbin.com/jijelop/edit?html,output】

四、作用域插槽

使用一个可以复用的模板来替换已经渲染的元素(从子组件中获取数据)
注:template模板不会被渲染,渲染的是template标签内的内容 (v2.5.0版本之前)

//html
...

      

    //v2.5.0版本后,可在别的标签(比如p,span,div等)上用 slot,slot-scope,并渲染标签
    

{{prop.text}}

//js ... components:{ 'my-component':{ template:'
\ \ \
'//在子组件定义一个slot,写上要传递的数据 } }

【Demo实例https://jsbin.com/hawodox/edit?html,output】

五、访问slot

通过 this.$slots.name 访问

//html
...

    

我是标题

//js ... mounted:function(){ // 访问插槽 var header = this.$slots.header var text = header[0].elm.innerText var html = header[0].elm.innerHTML console.log(header) console.log(text) console.log(html) }

【Demo实例https://jsbin.com/zarewac/edit?html,console,output】

六、组件高级用法-动态组件

component元素 (vue 提供)

1、作用

动态挂载不同组件

2、实现

使用is属性实现

//html
...






//js
...
components:{
        'compA':{
            template:'
离离原上草
' }, 'compB':{ template:'
一岁一枯荣
' }, 'compC':{ template:'
野火烧不尽
' }, 'compD':{ template:'
春风吹又生
' } }, methods:{ handleView:function(tag){ this.thisView = 'comp' + tag } } data:{ thisView:'compA' }

【Demo实例 https://jsbin.com/gocarif/edit?html,output】

你可能感兴趣的:(slot分发内容)