[英]How do I add a body class when a Vue Component is in the viewport?
當用戶單擊路由器鏈接時,有沒有辦法可以將 class 添加到正文標簽中。 然后當他們離開視圖時再次刪除這個 class ?
原因是對於應用程序 shell 我有一個固定的 header 和頁腳。 所有視圖(Vue 組件)都將這兩個元素作為設計的一部分,除了需要刪除這兩個元素的一頁。
我想如果我可以動態添加一個主體 class,我可以添加下面的 CSS。 這可以做到嗎?
.minimal-shell .header,
.minimal-shell .footer{
display:none;
}
我在手機上,所以我為格式化道歉。 您可以僅提供基於道具的 class 。
<body class="[isInView ? 'view-class' : '']">
<Linker @click="goToView" />
</body>
Model:
data: function() {
return {
isInView: false;
}
},
methods: {
... ,
goToView() {
this.isInView = true;
this.$router.push({ path: 'view' });
}
}
正如您可以想象的那樣,有幾種方法可以滿足您的要求。
當您導航到路由組件(您在<router-view>
渲染的組件)時,這些組件將具有特殊的路由器生命周期掛鈎,您可以使用:
beforeRouteEnter (to, from, next) {
getPost(to.params.id, (err, post) => {
next(vm => vm.setData(err, post))
})
},
// when route changes and this component is already rendered,
// the logic will be slightly different.
beforeRouteUpdate (to, from, next) {
this.post = null
getPost(to.params.id, (err, post) => {
this.setData(err, post)
next()
})
},
更多關於這個的官方文檔
您還可以使用導航守衛 - 在路線導航期間的某個時間點調用的 function:
router.beforeEach((to, from, next) => {
// ...
})
更多關於這個也在官方文檔中
當然,您也可以在組件本身中觸發您想要的所有更改。 在您導航到的組件中 - 或您的<router-view>
的根組件中。 我的第一個想法是在watcher
中處理邏輯:
watch: {
$route: {
immediate: true, // also trigger handler on initial value
handler(newRoute) {
if (newRoute.params.myParam === 'my-param') {
document.body.classList.add('my-class');
}
}
}
}
我個人會在根布局組件中觀察route
,因為我喜歡為業務邏輯/身份驗證(而不是樣式)保留導航守衛。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.