vue.js 如何从父组件获取特定子组件对象属性?

ou6hu8tu  于 2023-02-13  发布在  Vue.js
关注(0)|答案(2)|浏览(155)

我想从父组件中获取一个子组件的"meta"属性,这可能吗?
我知道有一个使用emit方法的解决方案,但是有没有更简单的方法来实现它呢?

// Default.vue <-- parent component
<template>
  <h1>{{ pagetitle }}</h1>
  <router-view />
</template>

<script>
import { defineComponent } from 'vue'

export default defineComponent({
  name: 'LayoutDefault',
  
  computed: {
    pagetitle () {
      let title = this.$route.meta.title // <--- I want to access child's component meta here

      // if title not provided, set to empty string
      if (!title) title = ''

      return title
    }
  }
})
</script>
// router/routes.js
const routes = [
  {
    path: '/',
    component: () => import('layouts/Default.vue'),
    children: [
      {
        path: 'dashboard',
        name: 'dashboard', 
        meta: { title: 'Dashboard', auth: true, fullscreen: false }, // <--- TAKE THIS
        component: () => import('pages/dashboard.vue')
      }
    ]
  }
]
// pages/dashboard.vue <-- child component
<template>
  <div>
    dashboard content
  </div>
</template>

<script>
import { defineComponent } from 'vue'

export default defineComponent({
  name: 'Dashboard',
  meta: { // <--- this should be reachable from the parent component (Default.vue)
    title: 'Dashboard',
    auth: true,
    fullscreen: false
  }
})
</script>
0x6upsns

0x6upsns1#

您可以通过$route.matched获取组件信息。
下面是一个PoC:

const Dashboard = Vue.defineComponent({
  template: "<div>Some dashboard</div>",
  meta: { title: "Dashboard" },
})

const router = new VueRouter({
  routes: [{ path: "/", component: Dashboard }],
})

const app = new Vue({
  router,

  computed: {
    // Note that this takes the *last* matched component, since there could be a multiple ones
    childComponent: (vm) => vm.$route.matched.at(-1).components.default,
  },
}).$mount('#app')
<div id="app">
  <h1>{{ childComponent.meta.title }}</h1>
  <router-view />
</div>

<script src="https://unpkg.com/vue@2/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router@3/dist/vue-router.js"></script>

正如Estus Flash在注解中所建议的,我们可以使用定义了meta * 的最后一个匹配的组件 *,而不是最后一个匹配的组件。

vm.$route.matched.at(-1).components.default

与:

vm.$route.matched.findLast((r) => "meta" in r.components.default)
    .components.default
carvr3hs

carvr3hs2#

我可以从网上找到一些方法:
1.按this.$refs.REF_NAME.$data使用ref(如下所示:https://stackoverflow.com/a/63872783/16045352

  1. Vuex或复制存储背后的逻辑(如下所示:https://stackoverflow.com/a/40411389/16045352

相关问题