slot
slot是Vue中的插槽,在我理解中主要的意义是将父组件中的html结构传递给子组件,如果想传递参数的话可能会选择props。
在使用slot时,可以分为默认插槽,具名插槽和作用域插槽
默认插槽
//父组件
<test>
Hello Word
</test>
//子组件
//test.vue
<a href="#">
<slot></slot>
</a>
那么在父组件中的子组件之中加入的内容就会被传到子组件中,在slot部分进行显示,因为这种使用方法没有具体知名在哪个插槽中使用,所以为默认插槽或匿名插槽,而匿名插槽的v-slot属性值为defalut
在子组件中,可以传输的内容包括字符,html标签,其他组件
在子组件的slot中可以设置默认显示的内容,如果没有任何参数传入则会显示默认内容
具名插槽
//子组件
<div>
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
通过在子组件中为slot设置name属性,就可以使插槽变为具名插槽,而父组件在子组件中传入的数据会根据name属性传到指定的部分
//父组件
<div>
<template v-slot:header>
<h1>Here might be a page title</h1>
</template>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
<template v-slot:footer>
<p>Here some contact info</p>
</template>
</div>
通过将需要传入的部分用template包裹并加上v-slot属性,就可以实现将指定内容传到指定插槽中
作用域插槽
作用域插槽实现的主要功能是,当在父组件中想要传递数据时,只能访问父组件中的数据而不能访问子组件中的数据,而为了访问子组件中的数据就需要通过slot将子组件中的数据传到父组件中
//子组件
//test.vue
<div>
<!-- 设置默认值:{{user.lastName}}获取 Jun -->
<!-- 如果home.vue中给这个插槽值的话,则不显示 Jun -->
<!-- 设置一个 usertext 然后把user绑到设置的 usertext 上 -->
<slot v-bind:usertext="user">{{user.lastName}}</slot>
</div>
//定义内容
data(){
return{
user:{
firstName:"Fan",
lastName:"Jun"
}
}
}
子组件中通过在slot上使用v-bind绑定需要的数据,而在父组件中,在v-slot之后将传入的数据赋值给一个变量,在这个变量中使用需要的属性即可
//父组件
<div>
<test v-slot:default="slotProps">
{{slotProps.usertext.firstName}}
</test>
</div>
keep-alive
<keep-alive>
<component :is="chooseTabs">
</component>
</keep-alive>
将组件使用keep-alive进行包裹之后,组件就会保持状态,它能在组件切换过程中将状态保留在内存中,防止重复渲染 DOM ,同时他也能保存一些组件的状态,例如在切换页面的时候消失的组件使用keep-alive标签包裹之后,当再次返回这个页面时,组件会保留原有的数据和状态
没有评论