Updating elements outside of a component

2019-09-18 07:11发布

问题:

I'm using Laravel and Vue to create an app which has a master layout.blade file and then I'm using component and the VueRouter.

What I can't get my head around is how to achieve the following. Lets say I have two routes 'Home' and 'About' which call a dedicated home.vue and about.vue component files.

What if, outside of the component I have a H1 for the heading of the page contained in the master page. How would I go about updating that? Do I do it in route.js or the component file?

回答1:

The best way to approach this is to have a base component with all your static components i.e. nav menu, footer and router-view. I think you may be getting confused because you are creating your layout in blade, but it's easier to just have a blade file as an entry point that pulls in your scripts and css and gives Vue somewhere to mount your App.So you would have a blade file looking something like this:

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

        <title>My App</title>

        <link href="/css/app.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
       <div id="app">

       </div>
       <script src="/js/app.js"></script>
    </body>
</html>

You would then create your layout in a base component (normally App.vue) and pass that to your render function in app.js:

import App from './components/App.vue'

new Vue({
    router,
    render: h => h(App)
}).$mount('#app');

Then your App.vue would have something like:

<template>
  <nav-menu></nav-menu>
  <router-view></router-view>
  <app-footer></app-footer>
</template> 

<script type="text/javascript">
  import NavMenu from './components/NavMenu.vue'
  import AppFooter from './components/AppFooter.vue'

  export default{
    components:{
      NavMenu,
      AppFooter
    }
  }
</script>

This way you gradually build your app up with components. If you have a fancy header, that can also be a component you place on each page. I've put together a JSFiddle, obviously these aren't single file components, but it shows the basic idea of what I'm talking about: https://jsfiddle.net/k3r3uzpx/