【问题标题】:How to add custom properties to a page in VueJS / Gridsome如何在 VueJS / Gridsome 中向页面添加自定义属性
【发布时间】:2019-12-24 22:10:29
【问题描述】:

我正在开发一个 Vue / Gridsome 项目,想知道如何将变量从 Page 中导出到它的父级 Layout

这是我的页面代码:

<template>
  <Layout>
    <h1>About us</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Error doloremque omnis animi, eligendi magni a voluptatum, vitae, consequuntur rerum illum odit fugit assumenda rem dolores inventore iste reprehenderit maxime! Iusto.</p>
  </Layout>
</template>

<script>
export default {
  metaInfo: {
    title: 'About us'
  }
}
</script>

如何导出自定义属性,例如 Author

我想在Layout 上输出该属性:

<template>
    <h1>{{ page.author }}</h1>
    <slot/>
</template>

<script>
import SiteHeader from '@/components/SiteHeader.vue'
import SiteFooter from '@/components/SiteFooter.vue'

export default {
  components: {
    SiteHeader,
    SiteFooter
  }
}
</script>

<static-query>
query {
  metadata {
    siteName
  }
}
</static-query>

【问题讨论】:

    标签: vue.js gridsome


    【解决方案1】:

    您可以使用$emit 函数来实现这一点。

    子组件内部:

    $emit('custom-event', 'my value')
    

    然后在你的父母中你可以监听这个事件并捕捉到价值。

    @custom-event="myMethod"

    还有一个方法:

    methods: {
        myMethod (value) {
            console.log(value);
        }
    }
    

    这应该记录“我的价值”

    您可以在此处阅读有关自定义事件的更多信息:

    https://vuejs.org/v2/guide/components-custom-events.html

    【讨论】:

    • Imo 插槽是实现此功能的更好方法。并将所有数据保存在一个地方。
    【解决方案2】:

    Vue 使用单向数据流。因此,无法“从下方”更新数据。

    解决方法是使用命名槽。

    所以你的布局应该是这样的

    
    <template>
        <h1><slot name="author">Here is a default (fallback) content that would be replaced with content passed into slot. And it is optional.</slot></h1>
        <slot/> <!-- this is a default slot -->
    </template>
    

    你的页面组件应该看起来像

    <template>
      <Layout>
        <template v-slot:author>author here</template>
        <h1>About us</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Error doloremque omnis animi, eligendi magni a voluptatum, vitae, consequuntur rerum illum odit fugit assumenda rem dolores inventore iste reprehenderit maxime! Iusto.</p>
      </Layout>
    </template>
    

    【讨论】:

    • 这很有效,谢谢 :) 想知道是否有一种解决方法可以将布局上插槽的动态内容传递到布局上的组件属性中?
    • 您可以在插槽内放置任何您想要的东西 - 其他组件/道具/计算/方法输出。
    • 我的意思是有效地将插槽放置在组件道具中?所以 prop 会读取 slot 输出。
    猜你喜欢
    • 2011-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-09
    相关资源
    最近更新 更多