将道具从布局传递到组件

时间:2019-03-16 16:47:19

标签: vue.js nuxt.js

所以我对vue还是很陌生,我的googlefu可能还不够好,但是我想做的是从layout => global组件传递props。这有可能吗?我目前正在玩耍,并且具有这样的默认布局

布局/default.vue

<template>
  <div>
    <SiteNav/>
    <nuxt class="nuxt-container"/>
  </div>
</template>

<script>
import SiteNav from "../components/SiteNav"

export default {
  test: "corgi",
  components: {
    SiteNav
  }
}
</script>

components / SiteNav.vue

<template>
  <div>
    <nuxt-link to="/sign-in">Click to Sign In</nuxt-link>
    <nuxt-link to="/second-page">Click to Second Page</nuxt-link>
  </div>
</template>

export default {
  props: {
    test: {
      type: String,
      required: false,
      default: ""
    }
  },
  created() {
    this.$parent.$emit("update:layout", this.test)
  },
  render() {
    return this.$slots.default[0]
  }
}
</script>

我已经能够创建多个都使用此全局组件的页面,但是我无法成功地将道具从布局传递到全局组件。有办法吗?

2 个答案:

答案 0 :(得分:2)

好的,这是一个很好的选择。在nuxt中,您实际上可以在非父/子组件之间进行通信,并且可以使用它与布局中的另一个组件或布局本身从布局中包含的任何内容进行通信。

在您的组件中发出您想要的任何东西,因此它可以是@click或任何方法,但是对于您而言,您希望将其放在mounted()而不是created()中,否则会导致由于事件的生命周期而导致的错误。所以:

//Component.Vue

<template>
  <div>All your lovely stuff</div>
</template>

<script>
export default {
  mounted() {
      this.$nuxt.$emit('test', 'blah');
  }
}
</script>

然后在布局中监听发射的事件,然后在创建的此类中监听它。

//default.vue

created() {
    this.$nuxt.$on('test', data => {
      console.log(data+' emitted')
      })
    },

,并且在安装组件时,控制台将记录“发射的blah”。

您还应该像这样关闭监听:

beforeDestroy() {
      // $off method will turn off the event listner
      this.$nuxt.$off('test');
  },

答案 1 :(得分:1)

由于<SiteNav/>是默认设置。因此,您可以像这样监听事件:

<SiteNav @update:layout="updateLayout" />

然后,您定义一个updateLayout方法,其第一个参数将是您从以下方法发出的值:

this.$emit('update:layout', this.test);

请注意,您不得在$ parent对象上发出通知(这会使跟踪事件的来源变得更加困难)。

相关问题