当用户导航到特定路线路径时更新 parent 数据

Update the parent data when user navigates to a specific route path

我是 VueJs 的新手,正在尝试使用 Vue-route 设置 Web 应用程序,并希望在用户导航到特定 URL 时更新 <header> 样式,是否直接使用 "URL bar" 或 "navigation bar"。在这种情况下,我们有一个 parent 组件,其中包含 height_status 数据和模板上的一些 <router-links>

我已经使用 $emit 技术完成了 "navigation bar" 部分并且效果很好,但后来我尝试在 created 生命周期挂钩上使用它以更新 header 每当创建 /home 路由但事件侦听器将不会到达 parent_component。 我该如何解决这个问题?有更好的方法吗? 请看下面的代码:

Parent_component.vue

<template>
  <div id="app">

    <router-link to="/home" @height_size_ctrl="change_height">Home</router-link>
    <router-link to="/about">About us</router-link>
    <router-link to="/contact">Contact us</router-link>

    <header :class="height_status ? 'head-h-s' : 'head-h-m'"></header>

    <router-view/>

  </div>
</template>

<script>
export default {
  name: "Parent_component"
  },
  data() {
    return {
      height_status: false
    }
  },
  methods: {
    change_height(h) {
      this.height_status = h
    }
  }
}
</script>

router.js

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/home',
      name: 'home',
      component: Home
    },
    {
      path: '/about',
      name: 'about',
      component: about
    },
    {
      path: '/contact',
      name: 'contact',
      component: contact
    }
  ]
})

home.vue

<template>
  <h1>hello</h1>
</template>

<script>

export default {
  name: 'home',
  created: function(){
    return this.$emit("height_size_ctrl", true)
  }
}
</script>

你为什么不尝试 class 绑定到 routeroute name 类似的东西:

<div :class="{'height_status': this.$route == '/home'}">Header</div>

<div :class="{'height_status': this.$route.name == 'Home'}">Header</div>

您也可以更改路由器:

router.js

  {
    path: '/home',
    name: 'home',
    component: Home,
    meta: {
      headerClass: 'head-h-s'
    }
  }

在你的组件中

Parent_component.vue

computed: {
  headerClass() {
    return this.$route.meta.headerClass
  }
}

现在 headerClass 在模板中可用。

<header :class="headerClass"></header>

正如@kcsujeet 所说,class 绑定是我们可以做到这一点的好方法。在这种情况下,我们需要查看条件 this.$route.path。如果值等于 /home select 'head-h-m,否则 select .head-h-s.

<header class="head-sec" :class=" this.$route.path == '/home' ? 'head-h-m' : 'head-h-s'">

我们还可以使用 this.$route 访问其他 route 定义的属性。我建议看一下 router.js 文件。

routes: [
    {
      path: '/home',
      name: 'home',
      component: Home
    }