在没有子代/父代的组件之间共享数据-Vue

时间:2019-10-28 21:09:32

标签: vue.js vuejs2 vue-component

我有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组件,而要拥有一个子组件,而要拥有两个子组件。

有可能吗?

1 个答案:

答案 0 :(得分:0)

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

  1. uex

vuex是管理应用程序状态的最佳方法,但是对于小型项目而言,它要繁重得多

  1. customevent

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投射数据,并使用存储事件获取数据,并在更改customData值时分派存储事件:

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
  }
}
)