<template>
<div class="App">
<nav class="App__nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</nav>
<router-view/>
<footer>
© Awesome Company
</footer>
</div>
</template>
複製代碼
<template>
<div class="App">
<nav v-if="showNav" class="App__nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</nav>
<router-view/>
<footer v-if="showFooter">
© Awesome Company
</footer>
</div>
</template>
複製代碼
-說明:這種方法的一個問題是,您必須控制應用程序中某些元素的可見性,經過在Vue.js中處理全局狀態。雖然若是您不須要很是複雜的佈局而且只是想在某些上下文中隱藏某些元素,這多是正確的方法,但隨着應用程序的增加,這種方法可能會成爲維護的噩夢。html
// app.vue
<template>
<div class="App">
<router-view/>
</div>
</template>
// LayoutDefault.vue
<template>
<div class="LayoutDefault">
<nav class="LayoutDefault__nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</nav>
<main class="LayoutDefault__main">
<slot/>
</main>
<footer class="LayoutDefault__footer">
© Awesome Company
</footer>
</div>
</template
// home.vue
<template>
<layout-default>
<div class="Home">
<h1>Home</h1>
<p>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy
eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam
voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet
clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit
amet.
</p>
<h2>Amet sit</h2>
<p>
Eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam
voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet
clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit
amet.
</p>
</div>
</layout-default>
</template>
<script>
import LayoutDefault from '../layouts/LayoutDefault.vue';
export default {
name: 'Home',
components: {
LayoutDefault,
},
};
</script>
複製代碼
<component :is="SomeComponent"/>
複製代碼
// app.vue
<template>
<component :is="layout">
<router-view :layout.sync="layout"/>
</component>
</template>
<script>
export default {
name: 'App',
data() {
return {
layout: 'div',
};
},
};
</script>
// home.vue
<template>
<div class="Home">
<h1>Home</h1>
<!-- ... -->
</div>
</template>
<script>
import LayoutDefault from '../layouts/LayoutDefault.vue';
export default {
name: 'Home',
created() {
this.$emit('update:layout', LayoutDefault);
},
};
</script>
複製代碼
// 修改home.vue
<template>
<layout name="LayoutDefault">
<div class="Home">
<h1>Home</h1>
<!-- ... -->
</div>
</layout>
</template>
<script>
import Layout from '../layouts/Layout';
export default {
name: 'Home',
components: {
Layout,
},
};
</script>
// src/layouts/Layout.js
import Vue from 'vue';
export default {
name: 'Layout',
props: {
name: {
type: String,
required: true,
},
},
created() {
// Check if the layout component
// has already been registered.
if (!Vue.options.components[this.name]) {
Vue.component(
this.name,
() => import(`../layouts/${this.name}.vue`),
);
}
this.$parent.$emit('update:layout', this.name);
},
render() {
return this.$slots.default[0];
},
};
<templat
複製代碼