コンポーネント化の思想実現vue 2.0ページタイトル(document.title)の更新
最近reactを学ぶためにvueとreactでそれぞれhttps://cnodejs.org/簡易版を実現しました
vueバージョン:https://share.la/cnodejs/vueソースアドレス:https://github.com/ycloud/cno...
reactバージョン:https://share.la/cnodejs/react/ソースアドレス:https://github.com/ycloud/cno...
その中でreactのすべてのコンポーネントの思想は多くの利益を得た.
今までのvue2.0ページタイトル(document.title)の更新の実現構想の文章を見返しても、実現できますが、特に優雅ではないような気がします.
vueのSlotとコンポーネントのライフサイクルを組み合わせて、vueコンポーネントで次のように実現します.
titleコンポーネント
タイトル(document.title)を更新する必要があるページまたはコンポーネントの部分コードは、次のとおりです.
これでもっとオリジナルhtmlのラベルに似ています.
デモhttps://jsfiddle.net/ycloud/s...
react親子コンポーネント間でpropsでデータを転送すると、より簡単に実現できます.
vueバージョン:https://share.la/cnodejs/vueソースアドレス:https://github.com/ycloud/cno...
reactバージョン:https://share.la/cnodejs/react/ソースアドレス:https://github.com/ycloud/cno...
その中でreactのすべてのコンポーネントの思想は多くの利益を得た.
今までのvue2.0ページタイトル(document.title)の更新の実現構想の文章を見返しても、実現できますが、特に優雅ではないような気がします.
vueのSlotとコンポーネントのライフサイクルを組み合わせて、vueコンポーネントで次のように実現します.
titleコンポーネント
export default {
created () {
this.updateTitle()
},
beforeUpdate () {
this.updateTitle()
},
methods: {
updateTitle () {
let slots = this.$slots.default
if (typeof slots === 'undefined' ||
slots.length < 1 ||
typeof slots[0].text !== 'string') return
let {text} = slots[0]
let {title} = document
if (text !== title) document.title = text
}
}
}
タイトル(document.title)を更新する必要があるページまたはコンポーネントの部分コードは、次のとおりです.
title
...
import VTitle from '...path/Title'
export default {
components: {
VTitle
}
}
これでもっとオリジナルhtmlのラベルに似ています.
デモhttps://jsfiddle.net/ycloud/s...
react親子コンポーネント間でpropsでデータを転送すると、より簡単に実現できます.
import { Component } from 'react'
class Title extends Component {
componentWillMount() {
this.updateTitle()
}
updateTitle(props) {
const { children } = props || this.props
const { title } = document
if (children !== title) document.title = children
}
componentWillReceiveProps(nextProps) {
this.updateTitle(nextProps)
}
render() {
return null
}
}
export default Title