动态组件:
<component :is="变量名"></component>标签配合is属性,is里的变量名是注册的组件名。
动态组件切换会造成组件的频繁创建与销毁(多个组件使用同一个挂载点,动态切换)
组件缓存:
配合<keep-alive><component :is="变量名"></component></keep-alive>使用,组件缓存技术。
两个新的生命周期:
- activated激活状态时触发
- deactivated失去激活状态时触发
<template>
<div>
<button @click="comName = 'UserName'">账号密码填写</button>
<button @click="comName = 'UserInfo'">个人信息填写</button>
<p>动态切换:</p>
<div style="border: 1px solid red">
<keep-alive>
<component :is="comName"></component>
</keep-alive>
</div>
</div>
</template>
<script>
import UserName from './components/01/UserName.vue'
import UserInfo from './components/01/UserInfo.vue'
export default {
data() {
return {
comName: 'UserName',
}
},
components: {
UserName,
UserInfo,
},
}
</script>
<style></style>
组件插槽:(通过 slot 标签, 让组件内可以接收不同的标签结构显示)
语法:
- 组件内使用<slot></slot>占位
- 使用组件时在组件标签内例:<Pannel></Pannel>夹着的地方,传入标签替换slot
插槽默认内容:<slot></slot>内放置内容,作为默认内容
具名插槽:一个组件内有2处以上需要外部传入标签的地方
<Pannel>
<template #title>
<p>图片</p>
</template>
<template #content>
<img src="./assets/a.jpg" alt="" />
</template>
</Pannel>
语法:
- slot使用name属性区分名字
- template 配合v-slot:名字来分发对应标签(v-slot:可以简化成#)
作用域插槽:
- 子组件, 在slot上绑定属性和子组件内的值
- 使用组件, 传入自定义标签, 用template和v-slot="自定义变量名"
- 自定义变量名自动绑定slot上所有属性和值形成对象例:scope = {row: defaultObj}
<slot :row='obj'>{{obj.headImgUrl}}</slot>
-----------------------------------------------------------------
<myTable :arr="list">
<template v-slot='scope'>
<a :href="scope.row.headImgUrl">{{scope.row.headImgUrl}}</a>
</template>
</myTable>
自定义命令:(获取标签,扩展额外的功能)
语法:
- 全局注册:Vue.directive('指令名',{'inserted'(el){ //可以对el标签扩展额外的功能 } })
- 局部注册:directives:{'指令名':{ inserted(el){ //对el进行操作 } } }
- inserted方法:指令所在标签,被插入到网页上触发(一次)
- update方法:指令对应数据/标签更新时,此方法执行
Vue.directive('color',{
inserted(el,bin) {
el.style.color = bin.value
},
update (el,bin) {
el.style.color = bin.value
}
})
-------------------------------
export default {
directives: {
focus: {
inserted(el) {
el.focus()
},
},
},
}
-------------------------------
<input type="text" v-focus />
<h1 v-color="clo">我是标题</h1>