Add External script into vue.js - javascript

I would like to include into my vue.js application a simple javascript script with an external link to the library, this one:
<script type="text/javascript" src="https://my_site/index.js"></script>
<link rel="stylesheet" href="https://my_site/index.css" />
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
new Pbx(
{
"key1": 'value1',
"key2": 'value2'
},
{
'config': 'configValue'
}
);
});
</script>
I have this main.js file and I would like to keep external my script:
import Vue from 'vue';
import VModal from 'vue-js-modal';
import App from './App.vue';
import router from './router';
import store from './store';
import i18n from './i18n';
import VueScrollactive from 'vue-scrollactive';
import VTooltip from 'v-tooltip';
import './styles/index.scss';
export default new Vue({
el: '#myApp',
store,
router,
i18n,
render: h => h(App),
});
I would like to know how to include my library in a good way, I have tried to include my javascrupt here but I don't like it so much.
Thanks

I remember I had used jQuery without installing it in npm, as long as you place <script> tag of jQuery on top of script tag of the build files that is placed inside the generated html file you may able to access the $ variable of jQuery inside your app.
You may do something like creating a separate .js file for that variable you want to access. let pbx = new Pbx(data) and the pbx data is accessible throughout the app as long the placing of script tags is proper.
One thing though, document.addEventListener('DOMContentLoaded') might interfere with vue, however you can access the pbx variable to the mounted life cycle of App component if you want to access it immediately

Related

How to create service in Vue and use all this.$t, this.$alertify etc

I have a service file called message.vue
<script>
export default {
methods:{
alert(msg,title){
this.$alertify.alert( title,msg);
}
}
}
</script>
And I Use it like below.
import messageSvc from '#/shared/services/message'
export default {
methods:{
showMessage(){ messageSvc.alert( 'msg', 'title'); }
}
}
This not work, this.$alertify is null
My question are:
Is this the best way to create service in Vue?
Or how to make this.$alertify available in my service?
To reiterate #varit05 point, you need to add vue-alertify to your Vue instance. I have created this example for you using the example alerts that can be found on the GitHub page for VueAlertify.
Here is a GitHub link to the repo containing source code from my example.
This is the important part (should be in your entry point, like main.js, which would give your entire app access to that this.$alertify "service"):
import Vue from "vue";
import App from "./App.vue";
import VueAlertify from "vue-alertify";
Vue.use(VueAlertify);
Vue.config.productionTip = false;
new Vue({
render: h => h(App)
}).$mount("#app");
If things that you want to access are correctly defined, you can import Vue from 'vue'; and them acces Vue.alertify;
To answer your questions:
Yes. It is the best way to create a service/ NPM module.
You can take a reference of Vuex or VueAlertify to get more idea.
To make it available globally to all the Vue components, you need to call the global method Vue.use(plugin_name/service_name). In your case, it is $alertify then it should be as below
I believe you're using VueAlertify
import VueAlertify from 'vue-alertify';
Vue.use(VueAlertify);
However, you need to register the plugin/Service before Vue Instance is invoked.
Official docs for Plugins
Hope this helps!

Bundle VueJS Components to use same data

I'm trying to figure out how I can bundle some Components which use the same data (from an API) so I only need to make one call. I'm learning VueJS right now and I don't know if this is even possible or how it is called. So basicly what I'm trying to archive is this:
Create an index.js file which get's the data from the API and bundles the components which use this data (or parts of it).
Useing import {subComponent} from '#/components/bundle/' to get a specific component from that bundle while it uses the data delivered by index.js
Is this possible? Probably this is common but I don't know what it's called. How can I realize this?
So far I tried this:
view.vue:
<template>
<subComponent1/>
</template>
<script>
import {subComponent1} from '#/components/bundle';
export default {
name: 'view',
components: {
subComponent1
},
</script>
index.js (in components/bundle/):
<script>
import subComponent1 from './subComponent1'
import subComponent2 from './subComponent2'
export {
subComponent1 ,
subComponent2
}
</script>
The Components are standart single-file components and don't use data from index.js yet, but I'm already getting this error:
What am I doing wrong?

How can I insert a VueJS app into an existing page?

At this project I'm working on there is a legacy server-rendered web page and some components had problems I've been assigned to fix, and I convinced the team to rewrite those parts in Vue to kickstart our migration.
I wrote the whole mini-app using the Webpack template provided by Vue CLI and it works like a charm... in that specific environment.
If I npm run build the built index.html also works fine in a static server.
However, I can't seem to include the app in an existing page composed of many other elements. Shouldn't it be as simple as adding the <div id='myApp'></div> element to the HTML and loading the generated JS files?
If it helps, the legacy app is a Rails app using .erb templates and the JS files are being loaded through the main pipeline in application.js.
Does anyone know why nothing happens when I try this?
Edit: more information - this is how main.js looks before build:
/* eslint-disable */
import Vue from 'vue'
// UI components
import VueSelect from 'vue-select'
import DynamicForm from './components/DynamicForm/'
Vue.component('vue-select', VueSelect)
Vue.config.productionTip = false
const DynamicForms = new Vue({
el: '.dynamic-form',
render: h => h(DynamicForm)
})
Edit: I managed to get Vue to work by integrating Webpack to Rails with Webpacker. However I still have some problems regarding context:
This is my main.js in one of the Vue components. It was working fine until I tried the PropData stunt so I could reuse the component with different data in a few places.
/* eslint-disable */
import Vue from 'vue'
// UI components
import VueSelect from 'vue-select'
// import 'nouislider'
import DynamicForm from './components/DynamicForm/'
import fields from './fields'
import fieldRules from './field-rules'
Vue.component('vue-select', VueSelect)
Vue.config.productionTip = false
document.addEventListener('DOMContentLoaded', () => {
const el = document.createElement('div')
document.querySelector('.dynamic-form').appendChild(el)
const vm = new DynamicForm({
propsData: {
fields,
fieldRules
},
el,
render: h => h(DynamicForm)
})
})
This is DynamicForm/index.vue
<template>
<div id='app'>
<ParamList :fields='paramFields' :fieldRules='paramRules'></ParamList>
<Output></Output>
</div>
</template>
<script>
import Vue from 'vue'
import ParamList from './ParamList'
import Output from './Output'
export default Vue.extend({
props: [ 'fields', 'fieldRules' ],
name: 'DynamicForm',
components: {
ParamList,
Output
},
data () {
return {
paramFields: this.fields,
paramRules: this.fieldRules
}
}
})
</script>
<style>
</style>
The field and fieldData props are merely JSON/JSONP with some data I'm going to use inside those components. The idea is that I could write another main.js changing just the field and fieldData when initing the Vue instance.
What am I doing wrong?
I've managed to fix everything in a three-step change to my components.
Integrate Webpack into Rails using Webpacker. There's even a Vue template!
Change the root component (the one mounted at a real DOM element) to a Vue subclass using Vue.extend (so the module line # the .vue file read export default Vue.extend({ instead of simply export default {
Remove the render function from the new DynamicForm (the name I assigned Vue.extend to) so it renders its own template.
I hope it helps as it was quite a pain to me!

Import JS to Vue from node_modules

Forgive my lack of expertise, but I am attempting to integrate and import This Grid System Into my own Vue Setup and Im having some slight trouble. Now, I normally import Plugins like so:
import VuePlugin from 'vue-plugin'
Vue.use(VuePlugin)
and I'm then able to use the components of said plugin globally, however this is not a plugin and I'm having trouble pulling in/importing the needed components into my own components... suggestions?
If you use it via NPM:
First, install:
npm install --save vue-grid-layout
Then "register" it (probably a .vue - or .js - file):
import VueGridLayout from 'vue-grid-layout'
export default {
...
components: {
'GridLayout': VueGridLayout.GridLayout,
'GridItem': VueGridLayout.GridItem
}
If you use it via <script> tag:
Naturally, add it somewhere:
<script src="some-cdn-or-folder/vue-grid-layout.min.js"></script>
And "register" it (propably a .js file or another <script> tag):
var GridLayout = VueGridLayout.GridLayout;
var GridItem = VueGridLayout.GridItem;
new Vue({
el: '#app',
components: {
"GridLayout": GridLayout,
"GridItem": GridItem
},
And... in your templates
In both cases, you can then use <grid-layout ...></grid-layout> in your template.

how use npm packages with Vue SPA

i have created Vuejs app using vue-loader,now i need to use an installed npm package as follow :
var x = require('package-name')
Vue.use(x)
but i have this error :
Uncaught TypeError: plugin.apply is not a function
dose Vuejs require a special type packages or it can work with any JavaScript package and this error can be solved
There are many approaches.
I am adding with respect #smiller comment and thanks for sharing the link . I am adding information here in case the link someday not work .
Credit to this link :- https://vuejsdevelopers.com/2017/04/22/vue-js-libraries-plugins/
First approach of-course #crig_h
window.x = require('package-name')
There are certain drawback . don’t work with server rendering . Otherwise everything will work fine in browser as window is global to browser , any properties attract to it will be accessible to whole app.
The second approach is .
Use Import with the js portion in the .vue file , Like this.
if inside the '.vue' file.
<script>
import _ from 'lodash';
export default {
created() {
console.log(_.isEmpty() ? 'Lodash is available here!' : 'Uh oh..');
}
}
</script>
If you have seperate file for .js then same like this there will we no <script> tag.
And Third method
where ever in the project you import vue. You can write this statement
import Vue from "vue";
import moment from 'moment';
Object.definePrototype(Vue.prototype, '$moment', { value: moment });
This will set the relevant properties to to Vue . And you can use it any where like this . As Vue is global scope of app.
export default {
created() {
console.log('The time is ' . this.$moment().format("HH:mm"));
}
}
ADDED FOR CSS
you can do import in src/main.js file in vue.js project .
import './animate.css'
Also if you like to import in template .
Inside the template you can do this.
<style src="./animate.css"></style>
Also have a look on css-loader package . what it does ?
Plugins are specific Vue packages that add global-level functionality to Vue, so if you aren't using a Vue plugin then you don't need to register it with Vue using Vue.use().
In general there isn't any issue using non-vue-specific packages via npm but if you need to register something globally, you can usually get away with simply attaching it to window like so:
window.x = require('package-name');
Unfortunately none of these answers worked for me what i ended up doing is
export default {
computed() {
x () {
return require('package-name')
}
}
}
And then use it as x.functionName() or whatever
There is better solution ... First import your package in main.js
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
import Vue from "vue";
import App from "./App.vue";
import "package-name";
After that's you code inside mounted method as javascript
<script>
export default {
mounted() {
const any = require("package-name");
// your code as normal js
},
};
</script>

Categories