Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/110.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vue.js 在没有子/父组件的组件之间共享数据-Vue_Vue.js_Vuejs2_Vue Component - Fatal编程技术网

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

Vue.js 在没有子/父组件的组件之间共享数据-Vue,vue.js,vuejs2,vue-component,Vue.js,Vuejs2,Vue Component,我有一个html网站。我想在页面上实现一些vue js组件。 例如,在我的标题中,我希望有一个输入字段(一个vue组件) 在我的主html中,我有第二个vue组件,它显示来自第一个vue组件的一些搜索结果 <header><search-component></search-component></header> <main><list-component></list-component></ma

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


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

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

<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组件和一个子组件和二个子组件


这可能吗?

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

  • uex
  • vuex是管理应用程序状态的最佳方法,但对于小型项目来说,它要沉重得多

  • 自定义事件
  • 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
    });
    
  • 储藏
  • 您可以使用localstorage或sessionstorage强制转换数据,并使用storage event获取数据。更改customData值时,您将调度storage event:

    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
      }
    }
    )
    
    尝试eventbus,或更复杂的Vuex应用程序