# Vue學習#4 import & export ###### tags: `Vue 直播班 - 2022 春季班` `Vue` ## 為何要使用 import 怕同一個檔案的程式碼太過冗長,故可以使用 import,讓常用到的程式直接匯入不用在寫一次了! ## 在 import 前需要將程式碼 export 在 import 想要的程式碼之前需要將該程式執行 export ## export的種類 ### 1. 具名匯出 --- ### 把指定的那個程式碼匯出,需要給予特定名稱,匯入也要給一樣的名稱 ### 用在匯出函式庫比較多 ### 2. 預設匯出 --- ### 把那個js檔案的程式都匯出,不一定要給予特定名稱,匯入時再給予就可以了 ### 大多都使用預設 <font color='red'> !! 一個檔案可以有多個具名匯出</font> <font color='red'> !! 一個檔案只能有一個預設匯出</font>  ## export範例 -- export.js ```=JavaScript export const a=1; //匯出變數 export function fn(){ //匯出函式 console.log('123'); } export const arrowFun=()=>{ //匯出箭頭函式 console.log('arrow'); } export default { //預設匯出 fn(){ console.log('it is default export!'); } } ``` ## import範例 -- import.html ## <font color='red'> 要使用 import , script 要加上 type="module" </font> ```=HTML <script type="module"> import { a , fn , arrowFun } from './export.js'; //具名匯入 console.log(a); fn(); arrowFun(); ------------------- import defaultExport from './export.js'; //預設匯出 defaultExport.fn(); </script> ``` ## 教訓 <font color='red'> ESM 的檔案都要加上 module, 只要你的 js 裡面有使用到 import 都要使用 type module 因此 HTML script檔案 要加上 type="module" </font>
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up