组件化的思想实现 vue2.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组件


<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的标签了。

demo演示
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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值