vue3 中 如何跨页面传值

在Vue 3中,跨页面传值可以通过多种方式实现,具体选择哪种方法取决于应用的具体需求和页面间的关系。以下列举了几种常见的跨页面传值方法:

1. 路由参数与查询参数

当页面间通过路由进行跳转时,可以利用vue-router的路由参数或查询参数来传递数据。

  • 路由参数 :适用于动态路由,即路由路径中包含动态片段(如/:id)。在跳转时,直接将值赋给对应的动态参数。
js 复制代码
// 跳转并传递路由参数
import { useRoute, useRouter } from 'vue-router';

const router = useRouter();
router.push({ name: 'TargetPage', params: { id: someValue } });

// 接收路由参数
const route = useRoute();
const receivedId = route.params.id;
  • 查询参数 :在URL后面附加?key=value形式的查询字符串。适用于传递临时、非敏感的数据。
js 复制代码
// 跳转并传递查询参数
import { useRouter } from 'vue-router';

const router = useRouter();
router.push({ path: '/target', query: { inputInt: someValue } });

// 接收查询参数
import { useRoute } from 'vue-router';

const route = useRoute();
const receivedInputInt = route.query.inputInt;

2. Vuex状态管理

对于需要在多个页面间共享的数据,或者涉及复杂状态流转的情况,可以使用Vuex作为全局状态管理工具。

  • 定义状态与 mutations:在Vuex store中定义共享状态和相应的方法(mutations)来更新状态。
js 复制代码
// store.js
import { createStore } from 'vuex';

export default createStore({
  state: {
    sharedData: null,
  },
  mutations: {
    setSharedData(state, data) {
      state.sharedData = data;
    },
  },
});
  • 在页面中使用 :通过useStore钩子访问和操作全局状态。
js 复制代码
// 发送端页面
import { useStore } from 'vuex';

const store = useStore();
store.commit('setSharedData', someValue);

// 接收端页面
import { useStore } from 'vuex';

const store = useStore();
const sharedData = store.state.sharedData;

3. localStorage/sessionStorage

对于需要持久化存储并在不同页面间共享的数据,可以使用浏览器的localStoragesessionStorage API。

  • 存储数据
js 复制代码
// 存储数据
localStorage.setItem('sharedDataKey', JSON.stringify(someValue));
  • 读取数据
js 复制代码
// 读取数据
const storedData = JSON.parse(localStorage.getItem('sharedDataKey'));

4. Broadcast Channel API

对于浏览器同源下的多个标签页或窗口间的通信,可以使用BroadcastChannel API。

  • 发送数据
js 复制代码
// 创建广播通道
const channel = new BroadcastChannel('my-channel');

// 发送消息
channel.postMessage(someValue);
  • 接收数据
js 复制代码
// 创建广播通道
const channel = new BroadcastChannel('my-channel');

// 监听消息
channel.onmessage = function(event) {
  const receivedValue = event.data;
  // 处理接收到的数据
};

5. window.postMessage

对于跨窗口(如弹出窗口、iframe等)间的通信,可以使用window.postMessage API。

  • 发送数据
js 复制代码
// 向目标窗口发送消息
window.opener.postMessage({ data: someValue }, '*');
  • 接收数据
js 复制代码
// 监听`message`事件
window.addEventListener('message', function(event) {
  if (event.origin === expectedOrigin) {
    const receivedValue = event.data.data;
    // 处理接收到的数据
  }
}, false);

根据实际应用场景选择合适的方法,或者结合使用这些技术,可以有效地实现在Vue 3项目中跨页面传值。记得在使用时注意数据的安全性、隐私保护及浏览器兼容性问题。

相关推荐
灵感__idea1 天前
Hello 算法:让前端人真正理解算法
前端·javascript·算法
向葭奔赴♡1 天前
CSS是什么?—— 网页的“化妆师”
前端·css
黑犬mo1 天前
在Edge、Chrome浏览器上安装uBlock Origin插件
前端·edge
excel1 天前
🧩 Vue 3 watch 源码详解(含完整注释)
前端·javascript·vue.js
大前端helloworld1 天前
前端梳理体系从常问问题去完善-网络篇
前端·面试
excel1 天前
🌿 一文看懂 Vue 3 的 watch 源码:从原理到流程
前端
繁依Fanyi1 天前
让工具说话:我在 Inspira Board 里用 AI 把“能用、好用、可复用”落成了日常
前端
weixin_456904271 天前
C# 中的回调函数
java·前端·c#
kura_tsuki1 天前
[Web网页] LAMP 架构与环境搭建
前端·架构
yinuo1 天前
UniApp+Vue3多分包引入同一 npm 库被重复打包至 vendor 的问题分析与解决
前端