好的,这里有一个使用插件的解决方案。也许有更好的方法:
1)在
plugins/scroll.js
``` javascript
// https://vuejs.org/v2/cookbook/creating-custom-scroll-directives.html#Base-Example
import Vue from 'vue'
Vue.directive('scroll', {
inserted: function (el, binding) {
let f = function (evt) {
if (binding.value(evt, el)) {
window.removeEventListener('scroll', f)
}
}
window.addEventListener('scroll', f)
}
})
```
2)在项目中添加插件
nuxt.config.js
``` javascript
module.exports = {
head: { },
plugins: [
{ src: '~/plugins/scroll.js', },
]
}
```
3)使用
v-scroll
在菜单中定义自定义行为的指令
/layouts/default.vue
``` javascript
<template lang="pug">
div(v-scroll="shrinkNav")
b-navbar.text-center(toggleable="sm" type="light" sticky)
#myNav.mx-auto.bg-white
b-navbar-toggle(target="nav_collapse")
b-navbar-brand.mx-auto(href="/#home") Example.org
b-collapse#nav_collapse.mx-auto(is-nav='')
b-navbar-nav(justified, style="min-width: 600px").vertical-center
b-nav-item.my-auto(to='/#home') Home
#content.container
nuxt
</template>
<script>
export default {
methods: {
shrinkNav() {
var scrollPosition = document.documentElement.scrollTop || document.body.scrollTop
var nav = document.getElementById('myNav')
console.log(scrollPosition, nav)
if(scrollPosition >= 150) {
nav.classList.add('shrink')
} else {
nav.classList.remove('shrink')
}
},
},
}
</script>
<style>
nav.navbar {
margin: 0;
padding: 0;
}
#myNav {
border-radius: 0 0 10px 10px;
border: 2px solid purple;
border-top: none;
}
#myNav.shrink {
border: none;
}
</style>
```