9466-utm-tracker
v2.0.1
Published
Vue 3 hooks for handling UTM parameters in URLs and storing them in cookies
Readme
9466-utm-tracker
Vue 3 hook,用于处理 URL 中的 utm_source 参数并存储到 cookie 中。
安装
npm install 9466-utm-tracker前置要求
- Vue 3
- Vue Router 4
这个 hook 需要在 Vue Router 环境中使用,因为它依赖于 Vue Router 来获取 URL 参数。
使用方法
- 确保你的应用已经配置了 Vue Router:
// 在你的 router/index.ts 中
import { createRouter, createWebHistory } from "vue-router";
const router = createRouter({
history: createWebHistory(),
routes: [
// 你的路由配置
],
});
export default router;- 在组件中使用 hook:
import { useUtm } from "9466-utm-tracker";
export default {
setup() {
const { utmSource } = useUtm({
cookieExpireDays: 30, // 可选,默认30天
cookieDomain: ".example.com", // 可选
cookiePath: "/", // 可选,默认'/'
});
// utmSource 是一个 ref 对象,包含 utm_source 的值
console.log(utmSource.value); // 例如: 'google'
},
};hook 会自动:
- 在初始化时获取 URL 中的 utm_source 参数
- 如果 URL 中有 utm_source 参数,保存到 cookie 中(cookie 名: _9466_utm)
- 如果 URL 中没有 utm_source 参数,尝试从 cookie 中读取
- 当 URL 参数变化时,自动更新并保存新的 utm_source 值
支持的 URL 格式
支持以下格式的 URL:
- Hash 模式:
http://example.com/#/path?utm_source=google - History 模式:
http://example.com/path?utm_source=google
Cookie 存储
utm_source 参数会直接存储在名为 _9466_utm 的 cookie 中,例如:
_9466_utm=google特性
- 🚀 自动从 URL 中获取 utm_source 参数
- 📦 将 utm_source 保存到 cookie 中
- 🔄 如果 URL 中没有参数,则从 cookie 中恢复
- 💪 完整的 TypeScript 支持
- 🎯 Vue 3 组合式 API
- 🛣️ 支持 Vue Router 4 的 hash 和 history 模式
- 🔒 安全的路由参数处理
API
useUtm(options?)
主函数,返回一个包含 utm_source 和相关方法的对象。
选项
interface UseUtmOptions {
cookieExpireDays?: number; // cookie 过期天数,默认 30
cookieDomain?: string; // cookie 域名
cookiePath?: string; // cookie 路径
}返回值
{
utmSource: Ref<string>; // 响应式的 utm_source 值
getUtmFromUrl: () => string; // 从当前 URL 获取 utm_source 的方法
getUtmFromCookie: () => string; // 从 cookie 获取 utm_source 的方法
}许可证
MIT
