Nb
Study
.com
🔍 请输入搜索关键字
< prev1 / 4 more >

Vue3 中KeepAlive在嵌套路由中的使用及注意事项

<KeepAlive> 是一个内置组件,它的功能是在多个组件间动态切换时缓存被移除的组件实例。通过缓存不活动的组件实例,避免重复渲染。通常在动态组件或者路由组件中使用,可以保留组件状态或者提高性能。

假设router/index.js 如下:

javascript 复制代码
const routes = [
  {
    path: '/',
    component: () => import('../layouts/MainLayout.vue'),
    children: [
      {
        path: '/parent',
        component: () => import('../views/ParentView.vue'), // 父组件
        children: [
          {
            path: 'child1',
            component: () => import('../views/Child1.vue'),
            meta: { keepAlive: true } // 启用缓存
          },
          {
            path: 'child2',
            component: () => import('../views/Child2.vue')
          }
        ]
      }
    ]
  }
]

其中 App.vueMainLayout 中都有router-view 组件。该如何配置 keepalive呢?

代码如下:

App.vue 配置

html 复制代码
<!-- App.vue -->
<template>
  <!-- 注意在嵌套路由中使用 keep-alive -->
  <router-view  v-slot="{ Component }">
    <keep-alive :include="['MainLayout']">
      <component :is="Component" />
    </keep-alive>
  </router-view >
</template>

MainLayout.vue 配置

javascript 复制代码
<template>
<el-scrollbar class="flex-1 layout-main-content">
  <div class="flex-1 shadow bg-white p-3">
    <router-view v-slot="{ Component }" >
        <keep-alive :include="cachedRoutes">
          <component :is="Component" />
        </keep-alive>
      </router-view>
  </div>
</el-scrollbar>
</template>
<script lang="ts" setup>
const router = useRouter();
// 动态计算需要缓存的路由名称
const cachedRoutes = computed(() => {
  let arr =  router.getRoutes().filter((r) => r.meta?.keepAlive).map(r =>r.name);  
  // 过滤掉 undefined 值
  const validRoutes = arr.filter((name): name is string => name !== undefined);
  return validRoutes;
});
</script>

注意事项

component中了key的使用

如果component 中使用了key,可能会造成重复渲染,axios 多次请求。

javascript 复制代码
<component :is="Component" :key="$route.fullPath"/>

可以修改key的绑定或删除key,以生成稳定 Key。

javascript 复制代码
<!-- 修改后 -->
<component :is="Component" 
  :key="`${$route.name}-${JSON.stringify($route.params)}`"/>

生命周期

keepAlive组件特有的生命周期,可用于调试或进行智能缓存策略控制。

javascript 复制代码
onActivated(() => console.log('Activated'))
onDeactivated(() => console.log('Deactivated'))

如何灵活控制请求执行条件?

javascript 复制代码
<script setup>
import { ref, watch, onActivated } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()
const data = ref(null)
const hasLoaded = ref(false) // 请求状态标记

// 统一请求方法
const fetchData = async () => {
  if (hasLoaded.value) return
  try {
    const res = await axios.get(`/api/data/${route.params.id}`)
    data.value = res.data
    hasLoaded.value = true
  } catch (err) {
    console.error(err)
  }
}

// 常规加载
if (!hasLoaded.value) {
  fetchData()
}

// 监听路由参数变化
watch(() => route.params.id, (newVal, oldVal) => {
  if (newVal !== oldVal) {
    hasLoaded.value = false
    fetchData()
  }
})

// 缓存激活时刷新数据
onActivated(() => {
  if (Date.now() - lastLoadTime > 5 * 60 * 1000) { // 5分钟缓存
    hasLoaded.value = false
    fetchData()
  }
})
</script>

acme.sh 使用步骤

acme.sh 是一个开源的纯 Shell 脚本实现的 ACME 客户端,可用于自动化申请、续期和管理 SSL/TLS 证书,以下是使用 acme.sh 的详细步骤:

1. 安装 acme.sh

打开终端,执行以下命令进行安装:

bash 复制代码
curl https://get.acme.sh | sh -s email=your_email@example.com

或者使用 wget

bash 复制代码
wget -O -  https://get.acme.sh | sh -s email=your_email@example.com

上述命令中的 your_email@example.com 要替换成你自己的邮箱地址,此邮箱用于接收证书相关的通知。安装完成后,acme.sh 会自动添加一个 cron 定时任务,以实现证书的自动续期。

2. 选择验证方式

acme.sh 支持多种域名验证方式,常见的有以下几种:

  • HTTP 验证(HTTP-01):适用于可以通过 80 端口访问的 Web 服务器。acme.sh 会在 Web 服务器的特定目录下创建验证文件,Let's Encrypt 服务器会通过 HTTP 请求来验证文件的存在。
  • DNS 验证(DNS-01):适用于各种情况,尤其是无法开放 80 或 443 端口的场景。acme.sh 会在域名的 DNS 记录中添加特定的 TXT 记录,Let's Encrypt 服务器会通过 DNS 查询来验证域名所有权。
  • TLS-ALPN 验证(TLS-ALPN-01):通过 443 端口进行验证,适用于支持 ALPN 扩展的 Web 服务器。

3. 以 DNS 验证为例申请证书

3.1 配置 DNS 提供商的 API 密钥

如果你使用的是腾讯云 DNS,需要设置环境变量:

bash 复制代码
export Tencent_SecretId="your_secret_id"
export Tencent_SecretKey="your_secret_key"

your_secret_idyour_secret_key 替换为你自己的腾讯云 API 密钥。

3.2 申请证书

使用以下命令申请证书:

bash 复制代码
./acme.sh --issue --dns dns_tencent -d example.com -d *.example.com
  • --issue:表示触发证书申请流程。
  • --dns dns_tencent:指定使用腾讯云的 DNS 验证方式。
  • -d example.com:指定要申请证书的主域名。
  • -d *.example.com:指定要申请证书的泛域名(可选)。

4. 以 HTTP 验证为例申请证书

4.1 确保 Web 服务器可访问

确保你的 Web 服务器(如 Nginx、Apache)正在运行,并且可以通过 80 端口访问。

4.2 申请证书

使用以下命令申请证书:

bash 复制代码
./acme.sh --issue -d example.com --webroot /path/to/your/webroot
  • -d example.com:指定要申请证书的域名。
  • --webroot /path/to/your/webroot:指定 Web 服务器的根目录,acme.sh 会在该目录下创建验证文件。

5. 安装证书

申请成功后,需要将证书安装到 Web 服务器上。以 Nginx 为例,执行以下命令:

bash 复制代码
./acme.sh --install-cert -d example.com \
--key-file       /etc/nginx/ssl/example.com.key  \
--fullchain-file /etc/nginx/ssl/example.com.cer \
--reloadcmd     "systemctl reload nginx"
  • --install-cert:表示安装证书。
  • -d example.com:指定要安装证书的域名。
  • --key-file:指定私钥文件的保存路径。
  • --fullchain-file:指定证书链文件的保存路径。
  • --reloadcmd:指定安装完成后重新加载 Web 服务器的命令。

6. 自动续期

acme.sh 会自动添加一个 cron 定时任务,在证书到期前 30 天自动尝试续期。你可以通过以下命令查看 cron 任务:

bash 复制代码
crontab -l

如果需要手动触发续期,可以使用以下命令:

bash 复制代码
./acme.sh --renew -d example.com

7. 卸载 acme.sh

如果你不再需要使用 acme.sh,可以执行以下命令进行卸载:

bash 复制代码
~/.acme.sh/acme.sh --uninstall
rm -rf ~/.acme.sh

上述命令会移除 acme.sh 的安装目录和相关配置。

通过以上步骤,你可以使用 acme.sh 轻松地申请、安装和管理 SSL/TLS 证书。

Git本地文件夹关联远程仓库同时强制覆盖远程仓库的文件

如果已经通过 Git 创建了一个远程仓库,并且远程仓库中已经有一些文件(如README.md 等),而本地有一个文件夹,希望将本地文件夹与远程仓库关联,并强制覆盖远程仓库中的文件。

使用场景

比如通过github或gitee创建了一个远程仓库,自动初始化了一些文件。同时通过create-vuevite 创建了一个项目,如何和远程的仓库关联呢?

如何我们直接拉取远程仓库到本地,因为文件夹已经存在,不能直接使用 create-vuevite 命令。

具体操作

具体代码如下:

bash 复制代码
git init
git add .
git commit -m "Initial commit with local files"
git push origin main --force

--force 是一种危险操作,因为它会强制覆盖远程仓库中的所有更改,可能会丢失远程仓库中的某些重要文件。如果你希望更安全地强制推送,可以使用--force-with-lease

html一键复制到微信公众号编辑器原理

一键复制到公众号(保留HTML格式)的原理总结,记录作为备忘:

微信公众号编辑器在粘贴时会优先解析text/html格式的内容(而非纯文本)。

因此,实现关键是强制让剪贴板同时存储text/htmltext/plain两种格式的数据,确保:

  • 公众号读取text/html:保留样式和排版。
  • 纯文本作为备用:防止不支持HTML的场景丢失内容。

实现原理

1、使用现代浏览器(navigator.clipboard API)**

1)创建多格式数据

使用ClipboardItem封装text/htmltext/plain格式的内容:

javascript 复制代码
const htmlBlob = new Blob([htmlContent], { type: 'text/html' });
const textBlob = new Blob([textContent], { type: 'text/plain' });
const items = [new ClipboardItem({ 'text/html': htmlBlob, 'text/plain': textBlob })];

2)写入剪贴板
通过navigator.clipboard.write(items)直接写入剪贴板,浏览器会自动处理格式优先级

2、传统浏览器(document.execCommand

1)模拟选中HTML内容

将HTML放入隐藏的textarea并选中内容:

javascript 复制代码
const dummy = document.createElement('textarea');
dummy.value = htmlContent; // 注意:此处实际存储的是纯文本,但包含HTML标签
dummy.select();

2)触发复制命令

通过document.execCommand('copy')复制选中内容。

关键技巧:虽然textarea内容是纯文本,但部分浏览器(如Chrome)会保留复制时的上下文格式(如从富文本编辑器复制的HTML)。

完整示例代码

html 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>一键复制 HTML 到微信公众号</title>
</head>

<body>
    <!-- 复制按钮 -->
    <button id="copyBtn">复制到公众号</button>
    <!-- 要复制的内容,设置为隐藏 -->
    <div id="content" style="display: none;">
        <p style="color: red;">红色文字</p>
        <p style="font-size: 20px;">大号字体文字</p>
    </div>

    <script>
        document.getElementById('copyBtn').addEventListener('click', async function () {
            const content = document.getElementById('content').innerHTML;
            try {
                // 尝试使用现代的 Clipboard API
                if (navigator.clipboard) {
                    const htmlBlob = new Blob([content], { type: 'text/html' });
                    const textBlob = new Blob([content], { type: 'text/plain' });
                    const items = [
                        new ClipboardItem({
                            'text/html': htmlBlob,
                            'text/plain': textBlob
                        })
                    ];
                    await navigator.clipboard.write(items);
                    alert('已按 HTML 格式复制!');
                } else {
                    // 旧浏览器使用 document.execCommand 方法
                    const dummy = document.createElement('textarea');
                    dummy.value = content;
                    document.body.appendChild(dummy);
                    dummy.select();
                    document.execCommand('copy');
                    document.body.removeChild(dummy);
                    alert('已按 HTML 格式复制!');
                }
            } catch (error) {
                console.error('复制失败:', error);
                alert('复制失败,请重试!');
            }
        });
    </script>
</body>

</html>

为什么公众号能解析HTML?

微信公众号编辑器本质是一个富文本编辑器,其粘贴逻辑为:

  1. 优先读取剪贴板中的text/html数据。
  2. 若不存在,则尝试解析text/plain中的HTML标签(部分编辑器支持)。

tailwindcss 4 集成vite报错:Failed to resolve "@tailwindcss/vite".

安装官网文档操作如下:

https://tailwindcss.com/docs/installation/using-vite

Install tailwindcss and @tailwindcss/vitevia npm.

bash 复制代码
npm install tailwindcss @tailwindcss/vite

Configure the Vite plugin

bashit 复制代码
# vite.config.ts
import { defineConfig } from 'vite'
import tailwindcss from '@tailwindcss/vite'
export default defineConfig({
  plugins: [
    tailwindcss(),
  ],
})

Import Tailwind CSS

Add an @import to your CSS file that imports Tailwind CSS.

bash 复制代码
@import "tailwindcss";

以上是官网的集成步骤,然而启动后报错:

Failed to resolve "@tailwindcss/vite". This package is ESM only but it was tried to load by require. See https://vite.dev/guide/troubleshooting.html#this-package-is-esm-only for more details. [plugin externalize-deps]

解决方案

vite.config.js/vite.config.ts 重命名为 vite.config.mjs/vite.config.mts

具体参考:https://vitejs.cn/vite5-cn/guide/troubleshooting.html

< prev1 / 4 more >