点击前端自学社区查看更多精彩




组件探索

组件命名两种格式
1. kebab-case
my-component-name

2. PascalCase
MyComponentName

Prop

Prop 命名格式
Prop  类型约束
props: {
title: String,
likes: Number,
isPublished: Boolean,
commentIds: Array,
author: Object,
callback: Function,
contactsPromise: Promise // or any other constructor
}


Vue.component('my-component', {
props: {
// 基础的类型检查 (`null` 和 `undefined` 会通过任何类型验证)
propA: Number,
// 多个可能的类型
propB: [String, Number],
// 必填的字符串
propC: {
type: String,
required: true
},
// 带有默认值的数字
propD: {
type: Number,
default: 100
},
// 带有默认值的对象
propE: {
type: Object,
// 对象或数组默认值必须从一个工厂函数获取
default: function () {
return { message: 'hello' }
}
},
// 自定义验证函数
propF: {
validator: function (value) {
// 这个值必须匹配下列字符串中的一个
return ['success', 'warning', 'danger'].indexOf(value) !== -1
}
}
}
})
Prop 传递值

单向数据流

禁用Attribute继承

Vue.component('my-component', {
inheritAttrs: false,
// ...
})

自定义事件 使用

事件名
this.$emit('to-A','参数')


<A @to-A='父级的自定义事件'></A>

methods:{
receiveSon:(e){
接收传递过来的参数
console.log(e)
}
}

插槽

具名插槽
// 子组件

<template>
<div>
//具名插槽
<slot name="head"></slot>
<h1>Son 组件</h1>
// 默认插槽
<slot></slot>
<Button @click="toParent">子向父 传递值</Button>
<slot name="foot"></slot>
</div>

</template>




//父组件
<template>
<div>
<h1>Father 组件</h1>
<hr>
<Son @receiveToParent="receiveToSon">
<template v-slot>
<h1>我是默认插槽</h1>
</template>
<template v-slot:head>
<hr>
<h1>我是具名插槽 head</h1>
<hr>
</template>
<template v-slot:foot>
<hr>
<h1>我是具名插槽 foot</h1>
<hr>
</template>
</Son>

</div>
</template>

2020前端技术面试必备Vue:(二)组件篇-LMLPHP

2020前端技术面试必备Vue:(二)组件篇-LMLPHP

2020前端技术面试必备Vue:(二)组件篇-LMLPHP

作用域插槽
注意
// 子组件
<template>
<div>
<slot :obj='obj'></slot>
<slot :obj='games'></slot>
</div>

</template>
<script>
export default {
name: 'Son',
data () {
return {
name: '测试',
obj: {
name: '张三',
age: 22
},
games: {
version: '版本:0.1',
name: '王者农药'
}
}
},

}
</script>





//父组件
<template>
<div>
<h1>Father 组件</h1>
<hr>
<Son @receiveToParent="receiveToSon">
// 通过v-slot:自定义 = “{}” 使用prop数据
<template v-slot:default= "{obj}">
{{obj.name}}
</template>
<templatev-slot:other= "{games}">
{{games.name}}
</template>
<template v-slot:head>
<hr>
<h1>我是具名插槽 head</h1>
<hr>
</template>

</Son>
</div>
</template>
插槽简写
 <template #head>
<hr>
<h1>我是具名插槽 head</h1>
<hr>
</template>

动态组件

组件上使用 keep-alive 来达到缓存效果
需要在router中设置router的元信息meta
  {
path: '/',
name: 'Father',
component: Father,
meta: {
keepAlive: true // 需要缓存
}
}
使用$route.meta的keepAlive属性进行判断
<el-col :span="24" class="content-wrapper">
<transition name="fade" mode="out-in">
//这里需要缓存,使用keep-alive标签包裹
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
//这里不需要缓存
<router-view v-if="!$route.meta.keepAlive"></router-view>
</transition>

</el-col>

2020前端技术面试必备Vue:(二)组件篇-LMLPHP

关注公众号,即可加入自学交流群学习



                 原创不易 觉得不错的话点一下在看😝


本文分享自微信公众号 - 前端自学社区(gh_ce69e7dba7b5)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

03-29 03:40