Vue插槽和组件化

112 阅读2分钟

一、插槽(模板化)

1.默认插槽

组件外部维护参数以及结构,内部安排位置

// SlotComponent
<template>
  <div>
    <h1>我是slot的标题</h1>
    <slot></slot>
  </div>
</template>

// 引入后使用
 <SlotComponent>
      <div>我是slot的内容</div>
 </SlotComponent>

image.png

2.具名插槽

以name标识插槽的身份,从而在组件内部做到可区分

// SlotComponent
<template>
  <div>
    <header>
      <slot name="header"></slot>
    </header>
    <main>
      <slot name="content"></slot>
    </main>
    <footer>
      <slot name="footer"></slot>
    </footer>
  </div>
</template>

// 引入后使用
<SlotComponent>
  <template v-slot:header>我是通过slot插入的标题</template>
  <template v-slot:content>我是通过slot插入的内容</template>
  <template v-slot:footer>我是通过slot插入的尾部</template>
</SlotComponent>

image.png

3.作用域插槽(slot传参)

2.6版本以前用slot-scope

// SlotComponent
<template>
  <div>
    //将 {message:"传参成功了",}包装到emitData中
    <slot :emitData="result"></slot>
  </div>
</template>

<script>
export default {
  name: "slotComponent",
  data() {
    return {
      result: {message:"传参成功了",}
    };
  },
};
</script>


// 引用后
 <SlotComponent>
      <template slot="default" slot-scope="slotProps">
       //将emitData,再包装到slotProps中使用
        <h1>{{slotProps.emitData.message}}</h1>
      </template>
    </SlotComponent>

2.6版本以后用v-slot(after) 外部做结构描述勾勒,内部做传参

// 引用后
<SlotComponent v-slot="slotProps">
    <h1>{{slotProps.emitData.message}}</h1>
</SlotComponent>


// 插槽结构
<SlotComponent v-slot="{emitData}">
    <h1>{{emitData.message}}</h1>
</SlotComponent>

串入一个重要知识点:数据的二次加工

watch/computed 响应流过于复杂

  • 方案一:函数 - 独立、管道 / 无法响应式
  • 方案二:v-html
  • 方案三:过滤器 - 追问:无上下文
   {{ time | format }}

面试题:jsx和Vue模板代码哪个更推荐 推荐模板代码 vue的模板编译步骤:template->render->vm.render->vm.render() template->render中会存在很多优化,比如diff之类 面试题:jsx中v-model 如何实现? 双向绑定 => 外层bind:value,内层@input

二、组件化

1.组件注册

传统模板化(全局)

使用Vue.component注册后,可以用在任何新创建的 Vue 根实例 (new Vue) 的模板中。

Vue.component('component', {
        template: '<h1>组件</h1>'
})
new Vue({
    el: '#app'
})

局部注册

import SlotComponent from "./components/SlotComponent.vue";
export default {
  components: {
    SlotComponent,
  },
  name: "App",
};

2.组件的高级引用

递归组件

nodetree

异步组件

router

动态组件

<component :is='name'></component>

3.混入mixin(逻辑混入)

    1. 应用: 抽离公共逻辑(逻辑相同,模板不同,可用mixin)
    1. 缺点: 数据来源不明确
    1. 合并策略 a. 递归合并 b. data合并冲突时,以组件优先 c. 生命周期回调函数不会覆盖,会先后执行,优先级为先mixin后组件

4.继承拓展extend(逻辑拓展)

    1. 应用: 拓展独立逻辑
    1. 与mixin的区别,传值mixin为数组
    1. 合并策略 a. 同mixin,也是递归合并 b. 合并优先级 组件 > mixin > extends c. 回调优先级 extends > mixin

5.整体拓展类extend

从预定义的配置中拓展出来一个独立的配置项,进行合并

6.Vue.use-插件

    1. 注册外部插件,作为整体实例的补充
    1. 会除重,不会重复注册
    1. 手写插件 a. 外部使用Vue.use(myPlugin, options) b. 默认调用的是内部的install方法