Last active
October 31, 2019 11:58
-
-
Save luiseok/85bb12e714f072861bf16dfdd7dc84fe to your computer and use it in GitHub Desktop.
vue js use cdn
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div></div> | |
</template> | |
<script> | |
export default { | |
name: "Component", | |
data: () => ({ | |
player: null, // 스크립트 로드 이후 객체를 저장 할 변수 | |
script: null, // 스크립트에 대한 정보를 가지고 있을 변수 | |
failed: false // 실패 요청시 예외처리를 하기 위한 플래그 변ㅅ구 | |
}), | |
beforeMount() { | |
this.script = document.createElement("script"); // script 태그 동적으로 생성 | |
this.script.src = "https://player.twitch.tv/js/embed/v1.js"; // 불러올 스크립트 파일 지정 (여기서 http 절대경로로 js파일 불러오면 됨) | |
this.script.id = "twitch-vid"; // 컴포넌트 destroy 시 삭제시킬 수 있도록 id 지정 | |
this.script.async = true; // asnyc 호출 | |
// 위의 스크립트 파일이 로딩되면, 아래 method 의 onScriptLoad() 를 호출하도록 event listener 등록 | |
this.script.addEventListener("load", this.onScriptLoad); | |
// 스크립트 로딩이 되지 않았을 경우의 예외처리를 위한 onScriptError() 를 event listener에 추가 | |
this.script.addEventListener("error", this.onScriptError); | |
document.body.appendChild(this.script); // html 태그 안에 삽입 | |
}, | |
methods: { | |
onScriptLoad() { // 스크립트 로드에 성공한 경우 실행되는 함수. 20번째 라인 참고 | |
// eslint-disable-next-line no-undef <- 이건 eslint를 사용하는경우 쓰이게 됨. 무시해도 괜찮음 | |
this.player = new Twitch.Player(this.$el, options); // 스크립트 로딩이 끝난 상황이므로, 객체를 위와같이 선언 | |
// 이후 this.player로 지지고 볶고 하면 됨 | |
}, | |
onScriptError() { | |
this.failed = true; | |
} | |
}, | |
beforeDestroy() { // 컴포넌트 소멸 되기 전, 불러왔던 스크립트에 등록되어 있던 이벤트 리스너들을 모두 해제해주어야 함. | |
this.script.removeEventListener("load", this.onScriptLoad); | |
this.script.removeEventListener("error", this.onScriptError); | |
this.script.remove(); // 스크립트를 body에서 삭제 | |
} | |
}; | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment