近期在做一个纯前端的简历项目,遇到一个问题难点。
背景:
纯前端(无后端),页面左侧是简历编辑区域,右侧是可以实时切换简历模板的,左侧编辑后,右侧简历预览可以实时随着数据更改而更新数据。最重要的是简历模板的热插拔实时切换更新
,纯前端实现方案。
首先在public/template.json中定义模板列表
为什么放在public文件夹?因为public文件夹不会被vite打包压缩,并且无论是打包还是开发状态运行,都可以直接通过/template.json
访问到对应的json文件获取到模板。
[
{
"id": "template111111",
"name": "简洁模板1",
"description": "简约而不简单的简历模板。",
"folderPath": "templateA",
"thumbnail": "preview.jpg"
},
{
"id": "template222222",
"name": "简洁模板2",
"description": "简约而不简单的简历模板。",
"folderPath": "templateB",
"thumbnail": "preview.jpg"
},
{
"id": "template33333",
"name": "开发版本",
"description": "供开发者参考开发的模板。",
"folderPath": "templateC",
"thumbnail": "preview.jpg"
}
]
获取简历模板列表的工具类
import type { Template } from '../types/template';
export const getTemplates = async (): Promise => {
try {
const response = await fetch('/templates.json'); // 使用绝对路径
if (!response.ok) {
throw new Error('无法获取模板列表');
}
return await response.json();
} catch (error) {
console.error('获取模板列表失败:', error);
return [];
}
};
使用pinia持久化存储用户切换模板的数据,这样用户下次在浏览器进入的时候看到的还是选择的模板
这里使用下面这个插件,开启pinia数据自动持久化
npm install pinia-plugin-persistedstate
useTemplateStore.ts中设置了用户选择的主题模板(另外还有主题色,不在本文章中介绍)
persist: true
开启pinia数据自动持久化 不需要自己另外再自己去写localStorage的更新插入等操作,十分方便!
import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Template } from "../types/template";
export const useTemplateStore = defineStore('templateStore', () => {
const currentTemplate = ref