Add all vue components to window array - javascript

I currently have a strange Vue setup due to our websites all using an old system.
What we have had to do is create an instance of Vue for each component (usually not many). What I want to do for all components is to pass their name and reference to the element into an array, just for reference when debugging issues on live issues.
app.js
import Vue from "vue";
import Axios from 'axios';
import inViewportDirective from 'vue-in-viewport-directive';
window.components = [];
Vue.component( 'video-frame', () => import('./components/VideoFrame.vue' /* webpackChunkName: "video-frame" */) );
Vue.prototype.$event = new Vue();
Vue.prototype.$http = Axios;
Array.prototype.forEach.call(document.querySelectorAll(".app"), (el, index) => new Vue({el}));
Now i'm adding the following code to each component, is there not a way I can do this once within my app.js and have all the components automatically do the following:
mounted() {
window.components.push({
tag: this.$vnode.tag,
elm: this.$vnode.elm
});
},

You can use a global mixin like this:
Vue.mixin({
mounted: function() {
window.components.push({
tag: this.$vnode.tag,
elm: this.$vnode.elm
});
}
});
That will ensure that code will run on the mounted hook on every single one of your Vue instances.
Reference: https://v2.vuejs.org/v2/guide/mixins.html

Related

How do I access Vue instance inside a js file in Vue3?

In Vue2, I was able to access my Vue instance to make use of components registered with Vue.
test.js
import Vue from 'vue'
export function renderLogin () {
Vue.toasted.show('Please login again', { type: 'error', duration: 2000 })
}
In the above code, I am able to access the toasted package as I have already registered it with Vue in my main.js. However, in Vue3 I'm unable to use the toasted package as I'm unable to access the Vue instance inside a js file.
Need help on how to access Vue instance('this') inside a js file.
After a day of searching, I was able to access the toasted component from the vue instance inside a js file.
First, we would have to export the app instance to be able to read it in a js file
main.js
export const app = createApp({
render() {
return h(AppWrapper);
},
});
Next, we would have to register our component in our globalProperties of our app's instance.
app.config.globalProperties.$toast = toast;
We can now import the app instance in our js file and access toast component
test.js
import { app } from '#/main.js'
app.config.globalProperties.$toast('Toast working fine', {
type: 'success',
duration: 2000,
})
Hope this helps someone out. Please let me know if there are other/better ways. Thank you
// Vue 3 Composition API
<script>
import { getCurrentInstance } from 'vue';
export default {
setup() {
const _instance = getCurrentInstance();
const vueInstance = _instance.appContext;
},
};
</script>
It's not exactly the way as in Vue2, but this will probably expose what you are looking for.
If you want to make a package globally available in Vue3 you probably need to add the following code to a plugin:
//* This will help for accessing the toasted instance in other files (plugins)
app.config.globalProperties.$toasted = toasted;
//* This will expose the toasted instance in components with this.$toasted
app.provide('$toasted', toasted);
With this you are able to get the toasted instance in the options api with: this.$toasted
And with the composition api:
const { $toasted } = _instance.appContext.app.config.globalProperties;
And in another plugin with:
constructor(app) { app.config.globalProperties; }
You can use provider/inject.
For example if you want to use axios across my components, provide axios in your main.js
import { createApp } from "vue";
import App from "./App.vue";
import axios from "axios";
const app = createApp(App);
app.provide("http", axios);
app.mount("#app");
Then in SFC component you could access by 2 ways:
// Composition API
<script>
import { inject } from 'vue'
export default {
setup() {
const http = inject("http");
http.get("https://jsonplaceholder.typicode.com/todos/1").then((response) => {
console.log(response.data);
});
}
}
</script>
// Vue 2 options API
<script>
export default {
inject: ["http"],
}
</script>
Original answer here.

Vue.js -Importing custom directive as ES6 Module

I have a rather specific question.
I'm using vue in my rails application through rails webpacker, to use vue components, I have to put a javascript pack tag in my layout and that references a javascript file that in turn renders the vue component, you can imagine that in total this approach has led me to make a lot of workarounds, but the one thing I still have left is a vue custom directive click-outside that I have had to add to each of my vue component generators, for example, here in filter-products.js
import Vue from "vue";
import filterProducts from "../../views/filter-products";
var element = document.getElementById("filter-products");
const props = JSON.parse(element.getAttribute("props"));
Vue.directive('click-outside', {
bind: function(el, binding, vNode) {
//bind logic
},
unbind: function(el, binding) {
//unbind logic
}
});
if (element != null) {
new Vue({
render: (h) => h(filterProducts, { props }),
}).$mount(element);
}
the custom directive code is actually big, so what I have in mind but am not sure how to do is one of two things:
Have the bulk for that custom directive in an ES6 Module and import that here and just use it directly.
Create a prototype for Vue that includes this custom directive and import it instead of importing vue from "vue".
Is either of the approaches better? and how would I achieve them? thanks!
Create a folder named directives and for each directive create a file to make your code more organized and maintenable especially in team :
import Vue from 'vue';
const directiveName = {
inserted: function(el, binding) {},
update: function(el, binding) {},
};
export default directiveName;
Vue.directive('directiveName', directiveName);//optional
then import it in any component like :
import directiveName from 'path-to-directives-folder/directives/directiveName'
then use it as follows :
data(){
...
},
directives:{directiveName}

Vue component inside legacy php/jquery project

I've got this big legacy web app based on Codeigniter and jQuery.
The plan is to phase out jQuery and start using Vuejs instead. We are replacing certain parts of the website step by step.
I have just installed Nuxtjs and got the file structure the way i like it inside the legacy project.
Now to the question. How can i access a Vue component from one of my legacy javascript files?
App.vue
<template>
<div id="app">
<HelloWorld msg="Welcome to Your Vue.js + TypeScript App" />
</div>
</template>
<script lang="ts">
import Vue from "vue";
import HelloWorld from "./components/HelloWorld.vue";
export default Vue.extend({
name: "App",
components: {
HelloWorld
}
});
</script>
main.ts
import Vue from "vue";
import App from "./App.vue";
import store from "./store";
Vue.config.productionTip = false;
new Vue({
store,
render: h => h(App)
}).$mount("#app");
I want to display my App.vue inside an ordinary php/html view.
I am doing something similar right now, the project was originally written using Thymeleaf and jQuery and now we are switching to Vue.
You can communicate between vue components and non-vue components in a few ways, none of them are "pretty".
Communication
Classic JavaScript events
Pretty straightforward
// legacy code
document.dispatchEvent(new CustomEvent('legacy-vue.something-happened', { detail: payload }))
// vue component
created () {
document.addEventListener('legacy-vue.something-happened', this.onSomethingHappened)
},
destroyed () { // don't forget to remove the listener!
document.removeEventListener('legacy-vue.something-happened', this.onSomethingHappened)
}
Exposing EventHub
Similar to the previous one, but you are using vue events instead. This is what i would recommend, because it's the Vue way of handling events and your goal is to vuetify your app.
// initialization
const hub = new Vue()
Vue.prototype.$eventHub = hub
window.$vueEventHub = hub
// legacy code
$vueEventHub.$emit('something-happened', payload)
// vue component
created () {
this.$eventHub.$on('something-happened', this.onSomethingHappened)
},
destroyed () {
this.$eventHub.$off('something-happened', this.onSomethingHappened)
}
Exposing whole components
The most flexible way, but it's hard to see what's going on where. Event based approaches the lesser evil in my opinion (it's easy to track events).
// vue component
created () {
window.vueTableComponent = this
}
// legacy component
vueTableComponent.fetchNextPage()
vueTableComponent.registerOnPageFetchedCallback(callback);
Summary
No matter which approach you pick, i recommend doing something like this:
Let's say that you have TableComponent. TableComponent has few props like apiUrl, emits row-clicked event, etc. It would be best to design the component without thinking about your legacy code at all, and then create it's legacy wrapper because at one point it will be used both with vue-only screens and with mixed-screens (with both legacy components and vue components). An example:
LegacyTableComponentWrapper.vue
<template>
<table-component
:api-path="apiPath"
#row-clicked="onRowClicked"
ref="table-component"
/>
</template>
export default {
data: () => ({
apiPath: null
}),
methods: {
onRowClicked (row) {
this.$eventHub.$emit('table-row-clicked', row) // notify legacy code
},
onApiPathDefined (payload) {
this.apiPath = payload
}
},
mounted () {
// legacy code might require the TableComponent to act differently
// and if you don't want the TableComponent to know whenever it's legacy or not
// you can always override one or more of it's methods.
this.$refs['table-component'] = this.overriddenImplementationOfXYZ
},
created () {
this.$eventHub.$on('define-api-path', this.onApiPathDefined)
},
destroyed () {
this.$eventHub.$off('define-api-path', this.onApiPathDefined)
}
}
It's sure more work at first, but will save you a headache later, when you will be working on your first view which is fully in vue and all that legacy communication stuff is in the way.

Loading an external script before loading components - Vue.js

In my Vue project, I would like to load a script from a server (e. g. https://myurl.com/API.js).
The script contains a variable, which I would like to use in my Vue component (view).
The problem is that when I load that scrip using the loadScript module:
import Vue from 'vue'
import LoadScript from 'vue-plugin-load-script';
Vue.use(LoadScript);
Vue.loadScript('https://quvia.cz:4443/portalAPI.js')
It is then loaded after the Vue component, so when try to console.log(externalScriptVariable), it is undefined. If I would setTimeout for 1 second, it would output the variable just fine.
What can I do in Vue.js to "await" the script loading, so it would load before every other Vue component?
You can use async/await
import Vue from 'vue'
import LoadScript from 'vue-plugin-load-script';
Vue.use(LoadScript);
(async function() {
await Vue.loadScript('https://quvia.cz:4443/portalAPI.js');
// other things after script loaded
})();
Or promise's then
import Vue from 'vue'
import LoadScript from 'vue-plugin-load-script';
Vue.use(LoadScript);
Vue.loadScript('https://quvia.cz:4443/portalAPI.js').then(() => {
// other things after script loaded
})
.catch(() => {
// error
});
In my case, the problems were resolved by the "window" scope. Also, if you need to access any Vue element inside the "onload" function, you need a new variable for the "this" instance.
<script>
import { mapActions } from "vuex";
export default {
name: "Payment",
methods: {
...mapActions(["aVueAction"])
},
created() {
let paywayScript = document.createElement("script");
let self = this;
paywayScript.onload = () => {
// call to Vuex action.
self.aVueAction();
// call to script function
window.payway.aScriptFunction();
};
// paywayScript.async = true;
paywayScript.setAttribute(
"src",
"https://api.payway.com.au/rest/v1/payway.js"
);
document.body.appendChild(paywayScript);
}
};
</script>
I worked with this on Vue 2.6.
What you could do is use the beforeCreate() lifecycle that vue provides and load the script from there.
import LoadScript from 'vue-plugin-load-script';
export default {
name: "App",
beforeCreate() {
LoadScript('https://quvia.cz:4443/portalAPI.js')
}
};
there are also other lifecycles that might suit your needs which you can find here: https://v2.vuejs.org/v2/guide/instance.html
Also, calling the LoadScript this in the main.js would make sure it is done before any components load

Vue Mixin properties are blank/empty/not reactive

I hope this question is not a duplicate. If it is so, please point me to the right directions.
I have a Vue application which is compiled with Webpack#NPM. I use mixin to propagate a property (roles) across all components. I update it with an ajax call from app instantiation. Problem is roles only updates for the <Root> component, not for all others.
////////////////////////
// app.js
////////////////////////
// import
window.axios = require('axios')
import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes.js'
// mixin
Vue.mixin({
data: function () {
return {
// property in question
roles: [],
}
},
methods: {
getRoles: function() { //////////// this method updates property.
// get
axios.get('/api/vcr/admin/roles')
// process
.then(response=>{
this.roles = response.data.data;
})
// error?
.catch(error=>{
this.toast(error.response.data.message);
})
},
},
});
// router
const router = new VueRouter({
mode: 'history',
routes: routes,
});
// app
const app = new Vue({
el: '#app',
components: { App: require('./views/App').default },
router,
base: '/saas/vcr/admin',
created: function() { ////////////// I update it here
this.getRoles();
}
});
////////////////////////
// Foo.vue
////////////////////////
<script>
export default {
mounted: function() {
console.log(this.roles) ////// returns an empty array
}
}
</script>
Do you know how to make roles reactive?
The global mixin you have created does not call the function that populates the roles property, it relies on the inheriting instance to do so. In your app "root" instance, you're doing that in the created life-cycle hook which calls getRoles on the mixin, but in the component Foo you are not calling it, so it will have its default empty value. The roles property is not shared, each component will get its own copy of it and will need to be populated.
You could change the mixin to do this for you, by adding the life-cycle created hook as you have done in the root instance. Here's an example of that. Note implementing that in the mix-in does not prevent or override later life cycle hooks from being run on the instances it is merged into. But, it will in your case make an API call for every component instance that is created, which probably isn't desirable.
If you want to only populate it once then share it between all components, it might make more sense to use Vuex and have a global state where roles is populated centrally and shared between all components in a reactive way.

Categories