react改变title_react根据路由动态修改页面title

1、在react的container组件中componentDidMount生命周期中

document.title="这是title名称"

2、或者在路由配置中使用onEnter事件修改

例如:

{document.title="这是title名称"}}/>

3、使用react-side-effect是一个类似Connect组件的容器,通常它被称为高阶组件。可能就会用到react-document-title插件

例如:

var React = require('react'),

PropTypes = require('prop-types'),

withSideEffect = require('react-side-effect');

4、封装公共组件。在react中,我们可以使用非常少的代码封装出一个公共组件,来修改每个路由的title。

import React from 'react'

import PropTypes from 'prop-types'

export default class ReactDocumentTitle extends React.Component {

setTitle() {

const { title } = this.props

document.title = title

}

componentDidMount() {

this.setTitle()

}

componentDidUpdate() {

this.setTitle()

}

render() {

return React.Children.only(this.props.children)

}

}

ReactDocumentTitle.propTypes = {

title: PropTypes.string.isRequired

}

这份代码是将react-side-effect和react-document-title合并。

使用该组件:

import ReactDocumentTitle from 'path/ReactDocumentTitle'

render() {

return (

)

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用以下方法修改路由的标题: 在Vue.js中,可以通过修改页面的标题来更改路由的标题。您可以使用`document.title`访问和更改当前页面的标题。 在使用Vue Router时,可以使用`beforeEach`导航守卫来监听路由变化,并在每次路由变化前更改页面的标题。下面是一个示例: ```javascript // main.js import Vue from 'vue'; import VueRouter from 'vue-router'; Vue.use(VueRouter); const routes = [ // 路由配置 ]; const router = new VueRouter({ routes }); // 在导航之前执行的导航守卫 router.beforeEach((to, from, next) => { document.title = to.meta.title || '默认标题'; // 设置页面标题 next(); }); new Vue({ router, render: h => h(App) }).$mount('#app'); ``` 上述代码中,`to.meta.title`表示目标路由对象的元信息中的`title`字段,您可以在路由配置中通过`meta`字段设置每个路由的标题。如果没有设置元信息或者`title`字段,则会使用默认标题。 在您的组件中,可以使用以下方式进行页面跳转,并且会自动修改页面的标题: ```javascript // 使用this.$router.push进行页面跳转 this.$router.push({ path: '/your-route-path', meta: { title: '新的标题' }}); ``` 在上述代码中,`path`表示要跳转到的路由路径,`meta`字段用于设置元信息,其中的`title`字段用来设置要修改页面标题。 这样,每次使用`this.$router.push`进行页面跳转时,都会同时修改页面的标题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值