简体   繁体   English

NUXT如何将数据从页面传递到布局

[英]NUXT how to pass data from page to layout

I am creating a very simple website.我正在创建一个非常简单的网站。 I want to change the Navbar elements depending on data set in navLayout on the page template.我想根据页面模板上navLayout中的数据集更改导航栏元素。 I want to pass the data to the layout, then use props to send it to the NavBar .我想将数据传递给布局,然后使用props将其发送到NavBar My issue is how to emit data from the page to the layout.我的问题是如何emit数据从页面发送到布局。

layouts/default.vue布局/default.vue

<template>
  <div>
    <NavBar />
    <div class="site-container">
      <nuxt />
    </div>
    <Footer />
  </div>
</template>
<script>
import NavBar from '~/components/NavBar.vue'

export default {
  components: {
    NavBar,
  }
}
</script>

pages/index.vue页面/index.vue

...
<script>
export default {

  data: () => {
    return {
      navLayout: 'simple'
    }
  },
  computed: () => {
    return {
    this.$emit('navLayout', value)
    }

  }
...
</script> 

One option is to use vuex for that.一种选择是为此使用 vuex。

First go into the store folder in your nuxt project and create a index.js file首先 go 进入你的 nuxt 项目的 store 文件夹并创建一个index.js文件

export const state = () => ({
   layout: 'Your default value',
})
    
export const mutations = {
  CHANGE_NAV_LAYOUT(state, layout) {
    state.layout = layout;
  }
}

Then inside any page/component you can call this.$store.commit('CHANGE_NAV_LAYOUT',value)然后在任何页面/组件中,您可以调用this.$store.commit('CHANGE_NAV_LAYOUT',value)

For your navbar component you create a computed property and refer it to the store layout value:对于您的导航栏组件,您创建一个计算属性并将其引用到商店布局值:

computed: {
     navLayout() {
         return this.$store.state.layout;
     }
}

You should use $emit from parent element, so the parent element to the page is layout page.您应该使用来自父元素的 $emit,因此页面的父元素是布局页面。 Here is sample:这是示例:

this.$parent.$emit("eventName");

Then listen action at layout on the Nuxt component.然后在 Nuxt 组件的布局上监听动作。

<Nuxt @eventname="actionHandler()"/> 

And here it is)在这里)

have u solved this problem.你解决了这个问题吗? i also want to known how to deal.我也想知道怎么处理。 i want to pass a value to layouts page, but i dont know how to do this.我想将一个值传递给布局页面,但我不知道该怎么做。

enter image description here在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM