【问题标题】:Update the parent data when user navigates to a specific route path当用户导航到特定路径路径时更新父数据
【发布时间】:2019-11-16 14:51:44
【问题描述】:

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

我已经使用$emit 技术完成了“导航栏”部分,它运行良好,但后来我尝试在created 生命周期挂钩上使用它,以便在/home 路由时更新标题创建但事件监听器不会到达 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>

【问题讨论】:

    标签: vue.js vue-component vue-router vue-cli


    【解决方案1】:

    您也可以更改路由器:

    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>
    

    【讨论】:

      【解决方案2】:

      为什么不尝试在routeroute name 上进行类绑定,例如:

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

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

      【讨论】:

      • 好主意,类绑定是正确的答案,但这种情况对我不起作用,因为类名称为head-h-shead-h-mthis.$route 也可能类似于 this.$route.path,具体取决于条件。所以我编辑了你的答案以匹配问题。谢谢@kcsujeet
      【解决方案3】:

      正如@kcsujeet 所说,类绑定是我们可以做到这一点的好方法。在这种情况下,我们需要查看条件this.$route.path。如果值等于/home,则选择'head-h-m,否则选择.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
          }
      

      【讨论】:

        猜你喜欢
        • 2021-02-09
        • 1970-01-01
        • 2012-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-14
        • 1970-01-01
        相关资源
        最近更新 更多