I'm new on VueJS ans Webpack. I've created a project with VueJS CLI and trying to work with it. I need to insert an CDN to my code.
When working with standard HTML, CSS & JS solutions, I'd include CDNs like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>False Merge</title>
<!-- CDN -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.16/sl-1.2.5/datatables.min.css"/>
<!-- StyleSheets -->
<link rel="stylesheet" href="public/stylesheets/index.css" />
</head>
<body>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.16/sl-1.2.5/datatables.min.js"></script>
<script src="public/javascripts/index.js"></script>
</body>
</html>
As you can see, you can add a CDN script with the HTML script tag, and start using it in the JS.
I'm trying to do the same with VueJS in a component. I've got the template and style sections ready.
Unfortunately, I don't know how to add in a simple way a CDN to use inmediately in the script tag within the Vue component. I tried to do this but it is not working.
<template>
<div class="index">
<div class="container">
<table id="table_dataset" class="display">
</table>
</div>
</div>
</template>
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.16/sl-1.2.5/datatables.min.js"></script>
<script>
export default {
name: 'Index',
data() {
return {
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
Is there a way to add a CDN (without Webpack or NPM) to a VueJS component?
Another option is to add the script inside index.html with
v-if
directiveInside the component file (
.vue
), if you want the script to be loaded set the flag totrue
:Unfortunately, no, you can't add a
<script>
tag to a specific component via template.In your case you have some options:
1: Use NPM
Propertly install the dependency using
npm
Steps:
For your case, you can check in
datatables
official page they do have a NPM package. I could be used like:And in your .vue file:
2: Add
<script>
tag toindex.html
Locate and a dd the
<script>
tag to yourindex.html
<script>
tag is clearly (and declaratively) added to the HTML source. The script will only be loaded once.<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.16/sl-1.2.5/datatables.min.js"></script>
to the end of theindex.html
file, preferably right before</body>
.3: Create the
<script>
tag programaticallyThe other alternative is to create the
script
tag programatically at the component, when the component is lodaded.Steps/Code: