最近为了学习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