import导入与slot的使用

vite配置

export default defineConfig({
  // 配置路径
  resolve: {
    alias: [{ find: "@", replacement: path.resolve(__dirname, "./src") }],
  },
  plugins: [vue()],
});

在配置上报没有path,网上查了下没有引入

const path = require("path");

后面还是出错

error when starting dev server:
Error: Dynamic require of "path" is not supported

想了想:vite采用的是ES6的动态导入机制,使用import导入方式,而不是 commonjs 那种require方式,网上给的答案是webpack打包工具提供的是基于commonjs的模块化方式,并不适用ES6这种方式。正确引入是

const path = require('path') // 导致报错

import path from 'path' // 使用import导入解决错误

slot的使用

子组件
<tem

plate>
  <table>
    <tr>
      <th>默认插槽:</th>
      <td><slot /></td>
    </tr>
    <tr>
      <th>具名插槽:</th>
      <td><slot name="footer" /></td>
    </tr>
    <tr>
      <th>传参插槽:</th>
      <td><slot name="bottom" :color="color" /></td>
    </tr>
    <tr>
      <th>传对象参插槽:</th>
      <td><slot name="object" v-bind="{ age, name }" /></td>
    </tr>
    <tr>
      <th>换个语法传参:</th>
      <!-- 这个语法我个人不推荐 -->
      <td><slot name="object" :="{ age, name }" /></td>
    </tr>
  </table>
</template>
<script>
export default {
  setup () {
    return {
      color: 'red',
      age: 34,
      name: 'FungLeo'
    }
  }
}
</script>

父组件

<template>
  <Child>
    这些文字将显示在组件默认插槽内
    <template v-slot:footer>
      这里的文字会显示在组件的具名插槽内
    </template>
    <template v-slot:bottom="scope">
      文字右边会有个颜色值 >>> {{scope.color}}
    </template>
    <template v-slot:object="scope">
      文字右边会有多个数据 >>> 名字:{{scope.name}},年龄:{{scope.age}}
    </template>
  </Child>
</template>
<script>
import Child from '@/components/child.vue'
export default {
  components: { Child }
}
</script>

对于vue3一个写法上是函数式的写法了!

setup的script标签与 setup()

在添加了setup的script标签中,我们不必声明和方法,这种写法会自动将所有顶级变量、函数,均会自动暴露给模板(template)使用。

这里强调一句 “暴露给模板,跟暴露给外部不是一回事”

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值