![](/img/trans.png)
[英]How to get localStorage value on client-side from global middleware using Nuxt.js
[英]How to Add Client-side Scripts to Nuxt.js?
我一直在閱讀有關插件的Nuxt.js文檔和用於添加腳本的config nuxt文件。 我都嘗試過,但沒有運氣。
我正在嘗試添加以下代碼(位於/static/js/scripts.js
):
$(window).scroll(function(){
if ($(window).scrollTop() >= 200) {
$('nav').addClass('fixed-header');
}
else {
$('nav').removeClass('fixed-header');
}
});
有人能幫助我嗎?
在常規HTML用法中,我只是在結束body標簽之前做script標簽(為了用戶體驗)。 我能夠將scripts.js
加載到Vue.js 2.0框架中,但是一旦將所有內容移至Nuxt.js,並嘗試使其適應Nuxt.js,除scripts.js
文件外,其他所有內容都可以正常工作。
[解決了]!
我想到了! 由於Nuxt.js文檔根本對我沒有幫助,因此我不得不參考Vue.js文檔。
因此,我基本上進入了包含導航欄的vue文件,我希望該類基於滾動顯示在其中。 我還必須修改JavaScript,使其對ESLINT友好...因此,下面的代碼與我在問題中所寫的內容相同。
<script>
export default {
name: 'MainNav',
data: function () {
return {
fixedOnScroll: false
}
},
methods: {
handleScroll () {
if (window.scrollY >= 200) {
this.fixedOnScroll = true
} else {
this.fixedOnScroll = false
}
}
},
created () {
if (process.browser) {
window.addEventListener('scroll', this.handleScroll)
}
},
beforeUpdate () {
if (process.browser) {
window.addEventListener('scroll', this.handleScroll)
}
}
}
</script>
解決之后,我必須在同一文件的模板標簽中使用vue綁定類。
<nav class = "navbar-expand-lg text-center" v-bind:class="{ 'fixed-header': fixedOnScroll }">
在那之后,一切都運轉良好!
Nuxt v1.4.0文檔中的官方指南在這里: https ://nuxtjs.org/faq/window-document-undefined#window-or-document-undefined-
如果需要指定僅在客戶端上導入資源,則需要使用process.browser變量。
例如,在您的.vue文件中:
if (process.browser) { require('external_library') }
如果要在多個文件中使用此庫,建議您通過nuxt.config.js將其添加到供應商捆綁包中:
build: { vendor: ['external_library'] }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.