vue bind html,javascript - How can I bind the html <title> content in vuejs? - Stack Overflow

本文探讨了如何在VueJS应用中将元数据处理与应用程序主体分离,通过创建一个独立的vanilla JS服务来处理OpenGraph等元数据。作者建议在main.js中导入并提供这个服务,然后组件可以通过依赖注入来使用。这种方式使得元数据服务具有可移植性,并允许在不同组件或使用不同框架的项目中复用,同时也支持针对不同场景实施不同的处理策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Just to chime in here. I have read that VueJS wants nothing to do with the meta stuff so I would do such things outside of the "VueJS" realm.

Basically make a plain vanilla js service like below. Here you could add all the functions to handle the meta data stuff such as the Open Graph data.

meta.js

export setTitle(title) {

document.title = title

}

Now we can import the service in main and then provide it to any component in the app who wants it. I could even use my meta service in other projects too which use different frameworks like React or Angular. Portability is super cool!

main.js

import meta from './meta'

new Vue({

router,

render: h => h(App),

provide: {

meta: meta

}

}).$mount('#app')

Here the component injects the meta service it wants to use.

someView.vue

export default {

name: 'someView',

inject: ['meta'],

data: function() {

returns {

title: 'Cool title'

}

},

created: function() {

this.meta.setTitle(this.title);

}

}

This way the meta service is decoupled from the app because different parent components can provide different versions of the meta service. Now you can implement various strategies to see which one is right for you or even different strategies per component.

Basically the inject walks up the component hierarchy and takes the meta service from the first parent who provides it. As long as the meta service follows a proper interface, you're golden.

Decoupling with DI is super cool 😃

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值