首页 > 其他分享 >单文件组件

单文件组件

时间:2022-09-06 14:13:36浏览次数:50  
标签:slot 文件 vue return default 插槽 组件

单文件组件

引入方式:

@1官方脚手架 @2挂载vm对象 @3组件引入并渲染到vm中

单文件组件有全局组件和局部组件 :

只是把一个组件单独写在一个.vue文件中,供别的组件引入然后注册

 

局部组件:

     var vm = new Vue({
            el: "#box",
            data: {},
            components: {
                Bar: {
                    template: ``
                }
            }
        })

 

全局组件:

//在主文件中引入其他组件
import Bar from "./xx.vue"
import Bar from "@/xx.vue"

 

//xx.vue组件文件
<template>

</template>

<script>
    export default{    
        data(){
       return{
       }
    }   } </script> <style scoped="scoped"> </style>

 

组件的属性

属性有两种写法:

简单声明

props:["prop1","prop2"]

 

详细描述

props: {
    propA: Number,        // 基础的类型检查 (`null` 匹配任何类型)
    propB: [String, Number],    // 多个可能的类型
    propC: {    type: String,
              required: true    // 必填的字符串
       },
    propD: {    type: Number,
              default: 100    // 带有默认值的数字
        },
    propE: {    type: Object,    // 带有默认值的对象或者数组填Array
        default: function () {    // 不建议直接填对象(因为对象直接量会一直占用内存),一般使用工厂函数,调用时才创建对象节省资源(面试)
                return { message: 'hello' }
              }
        },
    propF: {
              validator: function (value) {// 自定义验证函数返回为true就代表数据符合我们规定
            return ['success', 'warning', 'danger'].indexOf(value) !== -1
              }
        }
  }

 

 

v-slot:插槽

具名插槽 slot,slot-scope过时了

2.6.0使用v-slot

语法:v-slot:插槽名

语法糖:#插槽名

注意:

1、没有指定插槽名就是默认插入到插槽

2、不给插槽插入数据的话,就会使用组件的slot中的数据

3、插槽名不用使用引号引起来,直接写变量名插入的内容必须是template标签或者组件 不能是原生的元素

 

//vue主页面
<template>
<div>  
  <content2 :contentData="arr[1]">
        <template #slot1>
            <img src="../assets/xx.jpg">
        </template>
    
        <template #slot2>
            <p>在外部插入插槽的数据,不是子组件中的数据,也不是属性传进去的数据</p>
        </template>
        
        <template v-slot:slot3>
            666
        </template>         
        <p>没有指定插入到哪里</p>
  </content2>
</div>  
</template>

 

//组件页面
<template> <div class="content1"> <slot></slot> <slot name="slot1"></slot> <h1>{{contentData.title}}</h1> <h2>{{contentData.dt}}</h2> <slot name="slot3">你不给我数据到3号插槽中 我就会默认显示出来</slot> <p>{{contentData.text}}</p> <slot name="slot2"></slot> </div> </template> <script> export default{ props:{ contentData:{ type:Object, default:()=>{return {title:"0",dt:"0",text:"0"}} } } } </script>

 

标签:slot,文件,vue,return,default,插槽,组件
From: https://www.cnblogs.com/LIXI-/p/16660918.html

相关文章