I am using vue js in laravel, I need to use the global event bus. I created event-bus.js, and I import it to where I need to use it; when I click, events are generated, but there are no reactions from the listener. I tried everything, but it doesn’t work. Please help me, I have been working for 3 days
I tried to create an eventBus in app.js, but it didn't help either
My EditDiscountComponent
import { EventBus } from "../../../event-bus";
editDiscount () {
const data = {
discount_id: this.discountData.discount_id,
status: this.discountData.status,
type: this.discountData.type,
percentage:this.discountData.percentage,
amount:this.discountData.amount,
};
EventBus.$emit('update-discount', data);
this.languages.forEach(lang => {
if (lang.code && this.discountData[lang.code] !== undefined) {
data[lang.code] = this.discountData[lang.code];
}
});
this.$store.dispatch(actions.EDIT_DISCOUNT, data)
.then(res => {
if (res && res.data.status) {
// window.location.href = '/admin/discounts';
} else {
this.$store.commit(mutations.SET_SNACKBAR_SHOW, true);
this.$store.commit(mutations.SET_SNACKBAR_TEXT, res.data.message);
}
}).catch(console.error);
},
},
My ProductCOmponent
import { EventBus } from "../../../event-bus";
mounted() {
EventBus.$on('update-discount', ($data) => {
console.log($data);
});
this.getCategories();
this.getProducts();
},
I tried the callback of the function using a different method, but no results, and I tried this listener in the mount (), and this did not help
You can create your eventBus.js file inside src folder of your project which will look something like this
import Vue from 'vue'
export default new Vue()
And try to import it as shown below:
import EventBus from '#/eventBus'
Or this might help you https://alligator.io/vuejs/global-event-bus/
Related
How can I access a method or variable defined in the Vuex 4 store in my Blade file?
I am using a compiled app.js from vite. Obviously in the components of Vue js I can access the store, I wonder if it is also possible to do it in a blade file.
Vue js #app instance must be one of course.
If at the end of my blade file I write this
<script>
import {useStore} from "vuex";
import {onMounted, watch, ref, defineComponent} from 'vue'
export default {
setup() {
const click = () => {
store.commit('mutazione');
};
onMounted(() => {
alert('test');
})
const store = useStore();
return {
store,
click
}
},
}
</script>
the console gives me this type of error
Unexpected token '{'. import call expects exactly one argument.
First Leave laravel out of it.
It is purely vuex5.0 / Pinia https://pinia.vuejs.org job to do.
Best practice is Create the store of every type of data you need like
https://github.com/puneetxp/the check test directly in it totally in JavaScript you can see like create Store assume it is for Product data.
import { defineStore, acceptHMRUpdate } from "/js/vue/pinia.js";
export const useProductStore = defineStore({
id: "Product",
state: () => ({
rawItems: [],
}),
getters: {
items: (state) => state.rawItems
},
actions: {
addItem(product) {
this.rawItems.push(product)
},
removeItem(id) {
this.rawItems = this.rawItems.filter(i => i.id != id);
},
editItem(product) {
this.rawItems = this.rawItems.filter(i => i.id != product.id);
this.rawItems.push(product);
},
upsertItem(products) {
products.forEach(product => {
this.rawItems = this.rawItems.filter(i => i.id != product.id);
this.rawItems.push(product);
});
}
},
})
if (import.meta.hot) {
import.meta.hot.accept(acceptHMRUpdate(useActive_roleStore, import.meta.hot))
}
then we can use in your component
import { useProductStore } from "/js/vue/Store/Model/Product.js";
export default {
template: ``,
data() {
return {
useProductStore,
}
}
}
for use use it on useProductStore().items as my design you can make your own if you want.
What I'm Trying to do
I am new to Vue and I'm trying to replace getElementByID with $refs, but I get the following error:
Errors
Code
Here is the HTML:
<router-link to="/" ref="navOpt">
<div ref="activeOpt">
Here is the script:
// imports
import { ref, onMounted } from "vue";
// setup
setup() {
let navOpt = ref();
let activeOpt = ref();
onMounted(() => this.$refs.navOpt);
onMounted(() => this.$refs.activeOpt);
return { navOpt, activeOpt };
},
// Methods - check if the navOpt is active and removes css if it is
checkActiveRoute() {
if (this.navOpt.classList.contains("router-link-active")) {
this.activeOpt.classList.remove("hide-active");
}
},
// Created - call method on load
created() {
this.checkActiveRoute();
},
Tried Solutions
I have tried this but it gave me the same error.
Can someone help with this? Thanks!
ref values are automatically bound to the ref attribute in your elements, and there's no need to do onMounted(() => this.$refs.navOpt) since this doesn't have any effect, you should also use only one API (composition or options), but it's recommended to use the composition API, finally define the method just a function which should be called in the onMounted hook :
setup() {
let navOpt = ref();
let activeOpt = ref();
onMounted(() => {
checkActiveRoute()
});
function checkActiveRoute() {
if (navOpt.value.classList.contains("router-link-active")) {
activeOpt.value.classList.remove("hide-active");
}
}
return { navOpt, activeOpt };
},
I want to implement a feature that can register and unregister some modules when components created/destroyed, and my test like this:
// ../store/DMRTest.ts
const DMRTest = {
state: { name: 'DMR test ' },
mutations: {
getName(state) {
state.name += state.name;
}
},
actions: {},
getters: { NN(state) { return state.name; } },
};
export default DMRTest;
// App.vue
import DMRTest from '../store/DMRTest.ts';
// ...
async created() {
// Not works!
this.$store.registerModule('DMRTest', await import('../store/DMRTest.ts'));
// Works
this.$store.registerModule('DMRTest', DMRTest);
console.log(this.$store);
console.log(this.$store.state);
}
When I import the module statically, it will be registered correctly:
But when I use import function, the store registered the module like this:
How could I import the module dynamically?
I should append the default after the dynamic imported, question closed
Just so it is written with an example:
const store = new createStore(rootStoreModule);
const modules = ['moduleA', 'moduleB']
for(const module of modules) {
import(`./components/${ module.toLowerCase() }/store.js`)
.then( (obj) => { store.registerModule(module, obj.default); } )
}
I am running a simple Axios call like so:
.get('https://myAPI.com/')
.then(response => {
this.info = response.data
})
And then display the data through a v-for array loop on my components. The problem is that I am running this mounted Axios call on each component I use it for. For example, I have a component for desktop screens that uses this axios call to display data in sidebar, while my mobile screen component uses the exact same axios call too display in a header.
The problem is that I am running multiple calls to the same API since each component is using the mounted axiox function.
Is there a way to run this call once and then utilize the v-for loop on each component?
Use Vuex for such task.
I'll make a very simple example.
Install vuex and axios in your project
later create a file in your project call, store.js.
store.js
import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";
const store = new Vuex.Store({
state: {
info : []
},
mutations: {
updateInfo (state, info) {
state.info = info
}
},
actions: {
fetchData({commit}) {
axios.get('https://myAPI.com/')
.then(response => {
commit('updateInfo', response.data )
})
}
}
})
in your main.js import store.js file
import store from "./store";
new Vue({
...
store,
...
});
in your App.vue dispatch 'updateInfo' action.
App.vue
...
created() {
this.$store.dispatch("fetchData");
}
...
And in the component you want to use the info data component, set:
...
computed: {
info() {
return this.$store.state.info
}
},
...
and use info to render the elements with the v-for directive.
This info refers the array of elements you bring
OK, I've found a way to handle this without Vuex. My example: I have two components TrainingCourseComponent and CertificateComponent.
In TrainingCourseComponent:
data() {
return {
trainings : {},
},
methods:{
loadTrainingCenters(){
axios.get("/trainingCourse")
.then(({data}) => {
this.trainings = data;
Event.$emit('globalVariables', data);
});
}
}
created(){
this.loadTrainingCenters();
}
and you can do this in any other component but in this case CertificateComponent(you can define it in mounted() or created() method it doesn't matter:
data() {
return {
training_courses:{}
}
}
mounted(){
Event.$on('globalVariables', (trainings) => {
this.training_courses = trainings;
});
}
p.s. I guess you know but just in case Event is a global Vue instance defined in app.js that I use for different kind of stuff :)
app.js
/**
* some custom event
*/
window.Event = new Vue();
I am working on nuxt.js project and getting an error Cannot read property '$nuxt' of undefined when trying to access an event from plugin.
In ~/plugins/myPlugin.js
import Vue from 'vue';
this.$nuxt.$on('emit-height', (payload) => {
Vue.prototype.$bannerHeight = payload;
});
Importing in ~/plugins/nuxt.config.js
plugins: [
'~/plugins/get-main-banner-height.js',
]
this.$nuxt.$on works if I use it in any components but doesn't work in plugin as mentioned above.
In my component I am emitting the height.
methods: {
getMainBannerHeight() {
this.$nextTick(() => {
this.$nuxt.$emit('emit-main-banner-height', this.bannerHeight);
});
},
}
So, my question is "How to listen/capture event in plugins"?
You can reference app in context of nuxt plugin. Docs https://nuxtjs.org/api/context/
import Vue from 'vue';
export default ({ app }) => {
app.$on('emit-height', (payload) => {
Vue.prototype.$bannerHeight = payload;
});
}