您当前的位置: 首页 > 

杨林伟

暂无认证

  • 3浏览

    0关注

    3337博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Vue系列教程(14)- 插槽(slot)

杨林伟 发布时间:2021-06-25 10:29:47 ,浏览量:3

文章目录
  • 1. 引言
  • 2. Slot插槽
    • 2.1 案例代码
    • 2.2 代码分析

1. 引言

通过前面的章节,我们已经学会了使用计算属性computed来做内存优化,有兴趣的同学可以参阅下:

  • 《Vue系列教程(01)- 前端发展史》
  • 《Vue系列教程(02)- Vue环境搭建、项目创建及运行》
  • 《Vue系列教程(03)- Vue开发利器VsCode》
  • 《Vue系列教程(04)- VsCode断点调试》
  • 《Vue系列教程(05)- 基础知识快速补充(html、css、js)》
  • 《Vue系列教程(06)- Vue调试神器(vue-devtools)》
  • 《Vue系列教程(07)- Vue第一个程序(MVVM模式的引入)》
  • 《Vue系列教程(08)- 基本语法》
  • 《Vue系列教程(09)- 事件绑定》
  • 《Vue系列教程(10)- Model数据内容双向绑定》
  • 《Vue系列教程(11)- 组件详解》
  • 《Vue系列教程(12)- Axios异步通信》
  • 《Vue系列教程(13)- 计算属性(computed)》

本文主要讲解的是Vue的slot插槽特性

2. Slot插槽

Slot插槽在Vue.js中使用元素作为承载分发内容的出口,主要应用在组合组件的场景中。

需要注意的是Vue关注于视图,所以视图是不会写数据的。

举个例子,一般的页面布局如下:


  
    
  
  
    
  

如果使用插槽,那该如何写呢?下面来看看

2.1 案例代码

可以看到我们只关心布局代码定义,并把值绑定好即可,完整代码如下:

DOCTYPE html>



    
    Title
    
    



    
    
        
            
            
        

    


    
        Vue.component('aritcle', {
            template: '
\ \
    \ \
\
' }); Vue.component('aritcle-title', { props: ['title'], template: '
{{title}}
' }); //这里的index,就是数组的下标,使用for循环遍历的时候,可以循环出来! Vue.component("aritcle-content", { props: ["item", "index"], template: "
  • {{index+1}}、{{item}}
  • " }); var vm = new Vue({ el: "#app", data: { title: "阿甘兄的博客", contents: ['Java', 'Python', 'Vue'] } });

    运行结果: 在这里插入图片描述

    2.2 代码分析

    ① 首先定义了整体的模板:

    Vue.component('aritcle', {
               template: '
    \ \
      \ \
    \
    ' });

    ② 然后模板里面的插槽内容格式:

    // 定义aritcle-title插槽模板
     Vue.component('aritcle-title', {
                props: ['title'],
                template: '
    {{title}}
    ' }); // 定义aritcle-content插槽模板 Vue.component("aritcle-content", { props: ["item", "index"], template: "
  • {{index+1}}、{{item}}
  • " });

    ③ 最后在视图布局里声明模板(含插槽),并绑定Model

        
                
                
            
    

    注意:v-bind:title:title 作用一样,v-bind 可以省略不写。

    关注
    打赏
    1662376985
    查看更多评论
    立即登录/注册

    微信扫码登录

    0.1069s