生命周期
生命周期(Life Cycle)是指一个组件从创建 -> 运行 -> 销毁的整个阶段,强调的是一个时间段。
生命周期函数:是由 vue 框架提供的内置函数,会伴随着组件的生命周期,自动按次序执行。
动态组件 component
动态组件指的是动态切换组件的显示与隐藏。
<!-- 【注】is属性的值必须是字符串类型,Left是组件名 -->
<!-- <component :is="'Left'"></component> -->
<!-- 每次切换组件,原组件会被销毁,componentId是变量 -->
<!-- <component :is="componentId"></component> -->
<!-- 解决切换组件时,原组件销毁,即切换组件时,保留原组件,keep-alive中的component全部默认都被缓存 -->
<!-- keep-alive 的 include属性 可以指定那些组件需要被缓存(用英文逗号分隔) -->
<!-- keep-alive 的 exclude属性 可以指定那些组件不要被缓存 -->
<!-- 但是 include属性 和 exclude属性不能同时被使用 -->
<keep-alive exclude="MyLeft">
<component :is="componentId"></component>
</keep-alive>
【注】当组件被缓存时,子组件会自动触发组件的 deactivated 生命周期函数。
当组件被激活时,子组件会自动触发组件的 activated 生命周期函数。
插槽 slot
允许开发者在封装组件时,把不确定的、希望由用户指定的 部分定义为插槽。可以把插槽认为是组件封装期间,为用户预留的内容的占位符。
插槽用法
// 子组件(Son)
<template>
<p> 子组件 </p>
// 通过 slot 标签,为用户预留占位符
<slot>
// 如果父组件没有为插槽指定内容,那么备用内容就会生效
<p> 这是Son组件插槽的备用内容 </p>
</slot>
</template>
// 父组件
<template>
<Son>
// 为插槽指定内容
<p> Son组件插槽内容 </p>
</Son>
</template>
具名插槽 v-solt
// 子组件(Son)
<template>
<p> 子组件 </p>
// 通过 slot 标签,为用户预留占位符,给插槽指定一个具体的name名称
<slot name='title'> </slot>
<slot name='content'> </slot>
</template>
// 父组件
<template>
<Son>
// 为指定插槽指定内容,使用 v-solt 命令
//【注】v-solt只能用在组件 或 template 标签上
<template v-solt:title>
<p> 标题 </P>
</template>
// v-slot可以简写成#
<template #content>
<p> 内容 </P>
</template>
</Son>
</template>
作用域插槽
// 子组件(Son)
<template>
<p> 子组件 </p>
// mse 和 user 是一个自定义的属性名
<slot name='title' mse='hello slot' :user='username'> </slot>
<slot name='content'> </slot>
</template>
<script>
export default {
data() {
return {
username: '张三'
}
}
}
</script>
// 父组件
<template>
<Son>
//scope是自定义的变量,是一个对象,用于接收 title 插槽的数据
<template v-solt:title="scope">
<p> 标题 </P>
<p> {{scope}} </p>
</template>
// v-slot可以简写成#
<template #content>
<p> 内容 </P>
</template>
</Son>
</template>
自定义指令
私有自定义指令 directives
定义私有自定义指令
<script>
export default {
directives : {
color: {
// 为绑定到的 html 元素 设置颜色
// el 指的是绑定该指令的 DOM 对象
bind(el) {
el.style.color = 'red'
}
}
}
}
</script>
使用自定义指令
<p v-color>自定义指令</p>
动态绑定参数,使用自定义指令
<template>
<p v-color="color">自定义指令</p>
</template>
export default {
data() {
return {
//想要让自定义指令绑定动态参数,则该参数名必须和自定义指令名相同
color: 'red'
}
},
directives: {
color:{
//bind函数只会在绑定指令的时候调用一次,当 DOM 更新时 bind 函数不会被触发。
bind(el,binding){
//通过 binding对象的 .value属性,获取动态的参数
el.style.color = binding.value
}
//update 函数会在每次 DOM 更新时被调用
update(el,binding){
el.style.color = binding.value
}
}
}
}
如果 insert 和update 函数中的逻辑完全相同,则对象格式的自定义指令可以简写
directives: {
color(el,binding){
el.style.color = binding.value
}
}
全局自定义指令
在 main.js中
Vue.directive('color',function(el,binding){
el.style.color = binding.value
})