最近爲了學習react,用 vue 和 react 分別實現了 https://cnodejs.org/ 簡易版html
vue版本: https://share.la/cnodejs/vue
源碼地址: https://github.com/ycloud/cno...vue
react版本:https://share.la/cnodejs/react/
源碼地址: https://github.com/ycloud/cno...node
其中react一切皆組件的思想受益良多。react
如今回視以前的那篇 vue2.0 下對網頁標題(document.title)更新的一種實現思路 的文章,雖然也能夠實現,感受不是特別優雅。git
結合 vue的Slot 和 組件生命週期,用vue組件的方式實現以下:github
title組件segmentfault
<template> <h1 v-if="false"><slot>請輸入標題內容</slot></h1> </template> <script> 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 } } } </script>
須要更新標題(document.title)的頁面或組件部分代碼以下學習
<template> <div> <v-title>須要顯示的title</v-title> ... </div> </template> <script> import VTitle from '...path/Title' export default { components: { VTitle } } </script>
這樣就更像原生html的標籤了。this
demo演示
https://jsfiddle.net/ycloud/s....net
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