HMVue6.1【动态组件】
1 初始项目
npm install
npm audit fix
<template> <div class="app-container"> <h1>App 根组件h1> <hr> <div class="box"> div> div> template> <script> export default {} script> <style lang="less"> .app-container { padding: 1px 20px 20px; background-color: #efefef; } .box { display: flex; } style>
<template> <div class="left-container"> <h3>Left 组件h3> div> template> <script> export default {} script> <style lang="less"> .left-container { padding: 0 20px 20px; background-color: orange; min-height: 250px; flex: 1; } style>
<template> <div class="right-container"> <h3>Right 组件h3> div> template> <script> export default {} script> <style lang="less"> .right-container { padding: 0 20px 20px; background-color: lightskyblue; min-height: 250px; flex: 1; } style>
npm run serve
http://localhost:8080/
2 课件
3 动态组件 的基本使用
4 使用组件保持状态
4-1 问题分析
在离开Left进入Right时,Left被销毁了;从Right回到Left时,是一个新的Left,而不是原来的Left,所以原先Left的数据没了
4-2 问题验证
4-2 解决问题
4-2-1
4-2-2
4-2-3
4-2-4
inactive意思:失活、未激活、被缓存
5 keep-alive对应的生命周期函数
6 keep-alive的include和exclude属性
注意:这两个属性不能同时使用,只能使用其中一个或者不用
Right在被切出的状态下直接被销毁,而Left会被缓存而不会被销毁(include="Left" 或 exclude="Right" 效果一致)
7 扩展:组件注册名称与组件声明时name的区别
8 源码
<template> <div class="app-container"> <h1>App 根组件h1> <hr> <button @click="comName='Left'">展示Leftbutton> <button @click="comName='Right'">展示Rightbutton> <div class="box"> <keep-alive> <component :is="comName">component> keep-alive> div> div> template> <script> import Left from '@/components/Left.vue' import Right from '@/components/Right.vue' export default { data(){ return{ //comName 表示要展示的组件的名字 comName: 'Right' } }, components: { //如果在“声明组件export default”的时候,没有为组件指定 name属性 名称(/值),则组件的名称默认就是“注册components时候的名称”。 // (1) components注册名称主要作用:在中使用 // (2) 建议每个组件都在export default声明组件时指定name属性值,给即组件取名 Left, Right } } script> <style lang="less"> .app-container { padding: 1px 20px 20px; background-color: #efefef; } .box { display: flex; } style>
<template> <div class="left-container"> <h3>Left 组件 --- {{count}}h3> <button @click="count += 1">+1button> div> template> <script> export default { name: 'MyLeft', data(){ return{ count: 0 } }, created() { console.log('Left 组件被创建了!') }, destroyed() { console.log('Left 组件被销毁了~~~') }, // 当组件第一次被创建的时候,既会执行 created 生命周期,也会执行 activated 生命周期 // 但是,当组件被激活的时候,只会触发 activated 生命周期,不再触发 created。因为组件没有被重新创建 activated(){ console.log('组件被激活了,activated') }, deactivated(){ console.log('组件被缓存了,deactivated') } } script> <style lang="less"> .left-container { padding: 0 20px 20px; background-color: orange; min-height: 250px; flex: 1; } style>
<template> <div class="right-container"> <h3>Right 组件h3> div> template> <script> export default{ /* 当提供了 name 属性之后,组件的名称,就是 name 属性的值 对比: 1. 组件的 “注册名称” 的主要应用场景是:以标签的形式,把注册好的组件,渲染和使用到页面结构之中 2. 组件声明时候的 “name” 名称的主要应用场景: 结合标签实现组件缓存功能; 以及在调试工具中看到组件的 name 名称 */ name: 'MyRight' } script> <style lang="less"> .right-container { padding: 0 20px 20px; background-color: lightskyblue; min-height: 250px; flex: 1; } style>