简体   繁体   English

如何将 vanilla JavaScript 添加到 vue.js 项目?

[英]How to add vanilla JavaScript to vue.js project?

Good Day, I'm very new to vue.js and want a navbar, which ist transparent by default, but changes its background on scrolling.美好的一天,我对 vue.js 很陌生,想要一个导航栏,默认情况下它是透明的,但在滚动时会改变它的背景。 Unfortunately, it does not work.不幸的是,它不起作用。 I tried a fe solutions, but none of this worked.我尝试了一个 fe 解决方案,但这些都不起作用。 So this JavaScript code is an example from Stack Overflow, which works in a Fiddle.所以这个 JavaScript 代码是 Stack Overflow 的一个例子,它在 Fiddle 中工作。 If you need more information and/or code, please let me know.如果您需要更多信息和/或代码,请告诉我。

Navigation.vue导航.vue

<template>
    <div id="navigation"> 
        <nav class="nav-items"> 
            <router-link class="item" to="/home">Home</router-link>
            <router-link class="item" to="/about">About</router-link>
            <router-link class="item" to="/japan">Japan</router-link>
        </nav> 
    </div>
</template>

<script>
export default {
    name: 'navigation'
}

import scroll from '../assets/js/scroll.js';

</script>

scroll.js滚动.js

const navbar = document.querySelector('#navigation')

window.addEventListener('scroll', function(e) {
  const lastPosition = window.scrollY
  if (lastPosition > 50 ) {
    navbar.classList.add('colored')
  } else if (navbar.classList.contains('colored')) {
    navbar.classList.remove('colored')
  } else {
    navbar.classList.remove('colored')
  }
})

navigation.scss导航.scss

FYI: I've removed uneccessary code here.仅供参考:我在这里删除了不必要的代码。

#navigation {
    background: transparent;

    .colored {
        background: #fff;
        transition: 0.3s;
    }

}

Note: To view how to import custom code in a Vue component (general case), scroll down past the last <hr> .注意:要查看如何在 Vue 组件中导入自定义代码(一般情况),请向下滚动到最后一个<hr>


Vue is a JavaScript framework and therefore you can insert vanilla code anywhere in it and it will run perfectly fine. Vue 是一个 JavaScript 框架,因此您可以在其中的任何位置插入 vanilla 代码,它会运行得非常好。

IMHO, you issue is not about importing vanilla code.恕我直言,您的问题与导入香草代码无关。 It's about running it at the correct moment.这是关于在正确的时刻运行它。

You have to run your code inside mounted() hook, because that's when #navigation exists in DOM:您必须在mounted()挂钩中运行您的代码,因为那是DOM 中存在#navigation的时候:

 Vue.config.devtools = false; Vue.config.productionTip = false; Vue.component('navigation', { template: '#navigationTemplate', mounted() { window.addEventListener('scroll', () => document.querySelector('#navigation') .classList.toggle('colored', window.scrollY > 50) ) } }) new Vue({ el: '#app' });
 #app { min-height: 200vh; background: url("https://picsum.photos/id/237/1024/540") no-repeat center center /cover; } #navigation { background: transparent; position: fixed; top: 0; padding: 1rem; transition: 0.3s; width: 100%; box-sizing: border-box; color: white; } #navigation.colored { background: rgba(255, 255, 255, .85); color: black; } body { margin: 0; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <script id="navigationTemplate" type="text/template"> <div id="navigation"> <nav class="nav-items"> <a class="item" to="/home">Home</a> <a class="item" to="/about">About</a> <a class="item" to="/japan">Japan</a> </nav> </div> </script> <div id="app"> <navigation /> </div>


  1. your scroll.js can safely be written as:你的scroll.js可以安全地写成:
window.addEventListener('scroll',
  () => document.querySelector('#navigation')
  .classList.toggle('colored', window.scrollY > 50)
)
  1. Your SCSS seems incorrect:您的 SCSS 似乎不正确:
#navigation {
  .colored {
    declaration
  }
}

will apply declaration to any element with a class of .colored that's inside an element with the id of navigation .declaration应用于.colored类的任何元素,该元素位于idnavigation的元素 But your code toggles the class colored on #navigation .但是您的代码会切换#navigationcolored的类。 Therefore your SCSS should look like this:因此,您的 SCSS 应如下所示:

#navigation {
  &.colored {
    declaration
  }
}

Might not seem like much, but the & makes your code apply (or not).可能看起来不多,但&使您的代码适用(或不适用)。

  1. You probably want to apply transition to #navigation , as it should apply when it has the colored class and when it doesn't .您可能希望将transition应用到#navigation ,因为它应该在它具有colored类时应用,而当它没有时应用。 If you don't, the return transition (from .colored to :not(.colored) ) will not be animated.如果你不这样做,返回过渡(从.colored:not(.colored) )将不会被动画化。

For the record and to also answer your initial question, the proper way to import custom code into a Vue component is:为了记录并回答您最初的问题,将自定义代码导入 Vue 组件的正确方法是:

a) export your code as a function: a)将您的代码导出为函数:
(in scroll.js) (在滚动.js 中)

export function menuScroll = function() {
  /* your custom code here */
}

b) import it: b)导入它:
(in your component) (在你的组件中)

import { menuScroll } from 'path/to/scroll'

c) run it exactly where you need it: c)在你需要的地方运行它:
(ie: in mounted) (即:已安装)

export default {
  name: 'navigation',
  mounted() {
    menuScroll();
  }
}

Obviously, you want to rename the function in accordance with its purpose/role and the project's naming conventions.显然,您希望根据其用途/角色和项目的命名约定重命名该函数。

Last, but not least, if your function needs to take params, you might want to use it as a method:最后但并非最不重要的一点是,如果您的函数需要使用参数,您可能希望将其用作方法:

export function someName = function(...args) {
  /** do stuff with args **/
}

... and, in component: ...并且,在组件中:

import { someName } from 'path/to/it'

export default {
  name: 'whatever',
  methods: {
    someName,
    /* more methods... */
  }
}

just like that就这样

<template>
   .... your HTML
</template>

<script>
  export default {
    data: () => ({
      ......data of your component
    }),
    mounted() {
      let recaptchaScript = document.createElement('script')
      recaptchaScript.setAttribute('src', 'https://www.google.com/recaptcha/api.js')
      document.head.appendChild(recaptchaScript)
    },
    methods: {
      ......methods of your component
    }
  }
</script>

source : Link来源: 链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM