Маленький плагин для получения опций текущей страницы во фреймворке Nuxt. Порой ведь так хочется получить кастомные свойства, но подобной возможности в стандартной поставке я не нашел.
Создаем файл плагина currentpage.js в папке plugins.
class CurrentPage { constructor (route) { this.route = route } prop (name = undefined, defaultValue = false) { if (!name || !process.browser) return defaultValue if (!this.route || !this.route.matched || !this.route.matched[0]) return defaultValue let value = defaultValue Object.values(this.route.matched[0].components).some( component => { if (component.options && component.options[name]) { value = component.options[name] } } ) return value } } export default ({route}, inject) => { inject('currentpage', new CurrentPage(route)) }
Сложно не оценить мой неповторимый стиль в написании JS кода =)
Теперь подключаем плагин в конфигурации nuxt.config.js:
plugins: [ '~/plugins/currentpage' ],
После этого нам доступна инъекция, которая будет получать опции текущей страницы в Nuxt. Выглядит примерно так (~/pages/index.vue):
export default { customOption: 'customOptionValue', mounted() { console.log(this.$currentpage.prop('customOption', 'optional-default-value-if-property-not-present')) } }