简体   繁体   English

nuxt.js 获取 vue.js 组件中的默认磁头

[英]nuxt.js get default head in vue.js component

I am trying to get the head object that is configured by nuxt.config.js in a vue layout.我正在尝试获取由 nuxt.config.js 在 vue 布局中配置的头部 object。 In order to show the same title in an app bar as the page title.为了在应用栏中显示与页面标题相同的标题。

I know that you can alter the page title with the head function in a vue component.我知道您可以在 vue 组件中使用标题 function 更改页面标题。 But is it also possible to retrieve this information somehow?但是也有可能以某种方式检索这些信息吗?

<script>
export default {
  data () {
    return {
      title: head.titleTemplate // possible?
    }
  },
  head () {
      // here it is possible to change it but how about getting it?
  }
}
</script>

Another approach could be to get some data out of an page in the nuxt.config.js.另一种方法可能是从 nuxt.config.js 的页面中获取一些数据。 But I think this is not how the hierarchy is structured.但我认为这不是层次结构的结构。

Thanks for you help I am just starting to use javascript to code a website:)感谢您的帮助我刚刚开始使用 javascript 编写网站代码:)

(If I understand you correctly) You can use the changed callback to keep track of the latest meta info used (and thus the title). (如果我理解正确)您可以使用更改后的回调来跟踪使用的最新元信息(以及标题)。

Example:例子:

head() {
  return {
   changed: (info) => {
     this.title = info.title;
     console.log(info, info.title);
    },
  };
},
data() {
  return {
    title: '',
  };
},

In nuxt.config.js before export I have setted variable with a string of the title.在导出之前的nuxt.config.js中,我设置了带有标题字符串的变量。 Then added it to the head section and create a new env section: https://nuxtjs.org/api/configuration-env/然后将其添加到head部分并创建一个新的env部分: https://nuxtjs.org/api/configuration-env/

const title = `Site title`
export default {
    head: {
        title
    },
    env: {
        title
    }
}

This how I'm getting the title in any Vue component:这就是我在任何 Vue 组件中获得标题的方式:

export default {
  computed: {
    title () {
      return process.env.title
    }
  },
}

This helps you to keep your original title in process.env.title , even if you will want to change head.title dynamically.这可以帮助您将原始标题保留在process.env.title中,即使您想要动态更改head.title Did anyone found a better solution maybe?有没有人找到更好的解决方案? :) :)

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

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