Reputation: 527
I need your help very much... I have a Vue component and endpoint which gives me a script with a small menu and that script includes some actions. So, after my script is loaded its actions don't work on a page and I don't know why. Below the example code:
<template>
<div id="menu"></div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
},
mounted () {
// here I get a script which contains menu bar with actions
// css and styles
this.$http.get("https://endpointwithscript.com/menu").then(response => {
if (response.status === 200) {
//in that case script doesn't work. Eg click
var div = document.getElementById("menu")
div.innerHTML += response.body;
document.appendChild(div);
}
})
}
}
</script>
If I insert my downloaded script that way :
mounted () {
this.$http.get("https://endpointwithscript.com/menu").then(response => {
if (response.status === 200) {
document.write(response.body);
}
})
}
then script works but another html elements are overridden by that script and not displayed. How to download script, insert it on a page and keep all functionality ? Thank you!
Upvotes: 3
Views: 8418
Reputation: 417
You can try adding your external script into Mounted()
mounted() {
let yourScript= document.createElement('script')
yourScript.setAttribute('src', 'https://endpointwithscript.com/menu')
document.head.appendChild(yourScript)
},
Upvotes: 1
Reputation: 151
You could use v-html to include HTML-Code into a specific tag.
It seems the only way to implement a working script is by defining a new script element.
This worked for me here https://jsfiddle.net/nh475cq2/
new Vue({
el: "#app",
mounted () {
this.$http.get("https://gist.githubusercontent.com/blurrryy/8f7e9b6a74d1455b23989a7d5b094f3f/raw/921937ea99ff233dfc78add22e18868b32cd11c0/Test").then(res => {
if(res.status === 200) {
let scr = document.createElement('script');
scr.innerHTML = res.body;
document.body.appendChild(scr);
}
})
}
})
Upvotes: 0
Reputation: 61
<div class="menu"></div>
var div = document.getElementById("menu")
You are grabbing the element by ID, but gave it a class instead. Change the div to be <div id="menu"></div>
Upvotes: 0