简体   繁体   中英

How to proper use vue-router?

I want to exclude the h1 tag every time I go to different route in my Vue application.

Here's my app.vue :

<template>
    <div id="app">
        <img alt="Vue logo" src="./assets/logo.png">

        <h1>LANDING PAGE</h1>
        <router-view></router-view>
        <!--Path for login.vue-->
        <button @click="$router.push('/login')">LOGIN</button>
    </div>
</template>

<script>

    export default {
        name: 'app',
    }
</script>

And here's my login page, where I want only to display my design for login page only :

<template>
    <div>
        <h1>Login Page</h1>
    </div>
</template>

<script>
    export default {
        name: "Login"
    }
</script>

My route.js :

import Login from './components/LandingPage/Login';
import Register from './components/LandingPage/Register';

export default [
    {
        path: '/login', component: Login
    },
    {
        path: '/register', component: Register
    }
]

and lastly my main.js :

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import Routes from './routes';
import VueResource from 'vue-resource'

Vue.config.productionTip = false;
Vue.use(VueRouter);
Vue.use(VueResource);

const router = new VueRouter({
    routes: Routes,
    /* To remove # in the URL */
    mode: 'history'
});
new Vue({
    render: h => h(App),
    router: router
}).$mount('#app');

I didn't include the register.vue because it's just the same with login.vue .

基于目标网页网址的条件渲染:

<h1 v-if="$route.path === '/landing-page-url'">LANDING PAGE</h1>

Actually, there are three approaches to solve your problem:

  1. Just drop your <h1></h1> into your landing page component.
  2. You can use conditional rendering, like Psidom answered (just changed path to name ): <h1 v-if="$route.name === 'Landing'">Landing page</h1>
  3. You can have only one <h1></h1> in your main layout, and render current page title dynamically. Route Meta Fields come in rescue.
import Login from './components/LandingPage/Login'
import Register from './components/LandingPage/Register'

export default [
    {
        path: '/login',
        component: Login,
        meta: {
          title: 'Login',
        },
    },
    {
        path: '/register',
        component: Register,
        meta: {
          title: 'Register',
        },
    },
]

And then in your template :

<h1>{{ $route.meta.title }}</h1>

PS To navigate to another route in your template use <router-link></router-link> instead of button with click event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM