【问题标题】:Sharing Data Between Components without child/parent - Vue在没有子/父的组件之间共享数据 - Vue
【发布时间】:2020-02-24 03:55:03
【问题描述】:

我有 html 网站。我想在页面上实现一些 vue js 组件。 例如,在我的标题中,我想要输入字段(一个 vue 组件)。

<header><search-component></search-component></header>

在我的主 html 中,我有第二个 vue 组件,它显示来自第一个 vue 组件的一些搜索结果。

<main><list-component></list-component></main>

我将数据从搜索组件发送到列表组件吗?

HTML 是这样的:

<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>

    <body>
       <div id="app">
            <header>
                <search-component></search-component>
            </header>

            <main>
                <list-component></list-component>
            </main>
        </div>    
    </body>

</html>

当然这个html是简化版... 一切的重点是没有一个主 App.vue 组件和内部子组件一和子组件二。

这可能吗?

【问题讨论】:

  • 试试 eventbus,或者更复杂的应用 Vuex

标签: vue.js vuejs2 vue-component


【解决方案1】:

有很多方法可以共享来自不同组件的数据:

  1. uex

vuex 是管理应用程序状态的最佳方式,但对于小型项目来说更加繁重

  1. 自定义事件

customevent 比 vuex 更容易在您的应用中投射数据

var event = new CustomEvent('customE', {
        "detail": {
          //your data here
        }
      })
window.dispatchEvent(event)
//get data
window.addEventListener("customE", (e)=>{
//get your data here
e.detail
});
  1. 存储

您可以使用 localstorage 或 sessionStorage 来投射您的数据并使用 storage 事件来获取您的数据,您将在更改 customData 值时调度 storage 事件:

localStorage.customData = JSON.stringify('your Json data')
window.addEventListener('storage', (e) => {
//make sure you filter your data key
  if (e.key === 'customData') {
    //get your data here
    e.newValue
  }
}
)

【讨论】:

    猜你喜欢
    • 2016-04-27
    • 2020-09-24
    • 1970-01-01
    相关资源
    最近更新 更多