vue如何導入外部js文件(es6)


 

 

也許大家都是使用習慣了es5的寫法喜歡直接用《Script》標簽倒入js文件,但是很是可惜,這寫法。在es6,或則說vue環境下不支持


真的寫法是怎樣?


首先。我們要改造我們要映入的外部js文件,改成下面這個格式。主要是紅色方塊內部代碼,我們需要將我們的模塊“拋出”,讓人能獲取到

 

代碼:

[html]  view plain  copy
 
  1. function realconsole(){  
  2.     alert("hello.thanks use me");  
  3.   
  4. }  
  5.     export {  
  6.         realconsole  
  7.     }  


其次,到我們的寄主那里,我們需要導入,仿造其他的文件,寫法是這樣的:

代碼:

[html]  view plain  copy
 
  1. <template>  
  2.     <div class="teslist">  
  3.         <button @click="methods1">顯示console</button>  
  4.     </div>  
  5. </template>  
  6. <script src="../../lib/myconsole.js"></script>  
  7. <script>  
  8.     import { realconsole } from '../../lib/myconsole.js'  
  9.     export default {  
  10.         methods:{
  11.           methods1:function(){  
  12.               realconsole();  
  13.            }  
  14.     }}  
  15. </script>  
  16. <style>  
  17.     .teslist {  
  18.     }  
  19. </style>  


注意紅色叉的部分,那是我們es5的寫法,綠色才是正確的

接着是效果圖

 

 

 

二.直接引入的 不能用npm下載的

在view.vue中引入swiper.css和swiper.js文件

在view.vue中的代碼這樣寫:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<template>
...
</template>
<script>
import  swiper from  './swiper.js'
import  common from  '../common.vue'
export  default  {
     data(){
         return {
         }
     },
     mounted: function (){
         this .swippertab();
     },
     methods:{
         swippertab(){
              var  swiper =  new  Swiper( '.swiper-container' , {
                 pagination:  '.swiper-pagination' ,
                 slidesPerView: 3,
                 paginationClickable:  true ,
                 spaceBetween: 30
             });
         },
    
}
</script>
<style scoped>
@ import  './swiper.css' ;
</style>

注意一下的就是在swiper.js中需要改一下代碼,在最后面改成用export導出Swiper,並且代碼原有的amd格式的導出需要注釋掉

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM