Vue.js event bus - javascript

I'm working on a vue single page project,and I use an empty Vue instance as a central event bus.But there is some problem when firing a event.
eventbus.js
import vue from 'Vue'
export default new vue({})
a.vue
import bus from '~js/eventBus'
methods: {
go(name) {
bus.$emit('setPartner', name);
this.$router.go(-1);
}
}
b.vue
import bus from '~js/eventBus'
data() {
return {
contract: {
contractSubject: ''
}
}
},
mounted(){
bus.$once('setPartner', data => {
this.contract.contractSubject = data;
});
}
in b.vue file,I can recieve data,but I can't assign the value of data to 'this.contract.contractSubject'

I would comment, but point restrictions. It seems like you're only posting snippets of the code, so it's hard to get a full picture. I assume that you've already set this.contract to be an Object? I don't know what your data function looks like, and an error message would be helpful, but it sounds like you're trying to assign a field on an object that doesn't exist yet.
Edit
Thanks for the information. I'm not sure if your edit to b.vue was a mistake when you copied things over to stackoverflow, but based on the code you've provided, my guess is that you wrote data() in the wrong place. You have it inside mounted(), not as a key value of the component object, and thus this.contract won't access it.
I managed to get it working under the setup below
a.vue
import bus from './bus.js';
export default {
name: 'sitea',
methods: {
go(name) {
bus.$emit('setPartner', name);
}
}
}
b.vue
import bus from './bus.js'
export default {
name: 'siteb',
data() {
return {
contract: {
contractSubject: ''
}
}
},
mounted() {
bus.$once('setPartner', data => {
console.log(data);
this.contract.contractSubject = data;
});
}
}
More information

Related

Trouble setting up basic Pinia store with Vue options API

I am new to Pinia, and am having trouble setting up just a basic store. I have been following Pinia's own documentation, and cannot seem to read any state whatsoever from the vue component I'm mapping to the Pinia store.
In my app I have:
import { createPinia } from 'pinia';
export default function initApp(el) {
let app = createApp(MenuApp);
app.use(router).use(createPinia()).mount(el);
}
I set up a super basic Pinia store, just to get started:
import {defineStore} from 'pinia';
export const useTestPiniaStore = defineStore('testStore', {
state: () => {
return {
name: 'bob'
}
},
})
In my vue component I have:
<template>
<div class="menu-page">
<h1>{{name}}</h1>
</div>
</template>
<script>
import { mapState } from 'pinia';
import useTestPiniaStore from '#store/modules/piniaStore';
export default {
computed: {
...mapState(useTestPiniaStore['name']),
}
}
</script>
Pinia appears in my Vue dev tools, but no stores appear within it, and I get the error
Cannot read properties of undefined (reading 'name')
I don't understand what I am doing wrong here. If anyone can give some pointers that would be so appreciated.
mapState() requires two arguments, but you've passed it only one.
The 1st argument should be useTestPiniaStore, and the 2nd should be an array of state properties to map (or an object). It looks like you're trying to reference name from useTestPiniaStore, which would be undefined.
Your computed prop should look like this:
<script>
import { mapState } from 'pinia'
import { useTestPiniaStore } from '#/store'
export default {
computed: {
...mapState(useTestPiniaStore, ['name']), 👈
},
}
</script>
demo

VueJS - "this" is undefined in common function

I'm trying to extract a function for use across multiple components, but "this" is undefined and I'm unsure of the best practice approach of how to attach the scope so my function knows what "this" is. Can I just pass it as an argument?
Component:-
import goToEvent from "#/common";
export default {
name: "update",
methods: {
goToEvent
common function:-
let goToEvent = (event, upcoming=false) => {
this.$store.dispatch({
type: 'setEventsDay',
day: event.start_date
})
}
export default goToEvent
When I call goToEvent in my component, I get TypeError: Cannot read property '$store' of undefined. How do I avoid this?
In this situation I recommend to define eventable as a mixin :
const eventable= {
methods: {
goToEvent(event, upcoming=false) {
this.$store.dispatch({
type: 'setEventsDay',
day: event.start_date
})
}
}
}
export default eventable;
in your vue file :
import eventable from "#/eventable";
export default {
name: "update",
mixins:[eventable],
....
second solution :
export an object with the function as nested method then import it and spread it inside the methods option :
export default {
goToEvent(event, upcoming=false){
this.$store.dispatch({
type: 'setEventsDay',
day: event.start_date
})
}
}
then :
import goToEvent from "#/common";
export default {
name: "update",
methods: {
...goToEvent,
otherMethod(){},
}
//....
}
You're tagged with Typescript, so you need to tell TS that this actually has a value (note, I do not know VueJS, am using the generic Event types here, there is likely a more valid and correct type!)
First option, manually tell it what there is -
let goToEvent = (this:Event, event, upcoming=false) => {
Other option - tell it what type it is -
let goToEvent: EventHandler = (event, upcoming=false) => {
Of the two I personally prefer the second style for readability.
There are numerous ways to achieve this, here are some that I like to use in my projects:
Method 1: Mixins
Mixins are great for sharing a bunch of methods across components and also easy to implement, although one big con is that you will not be able to import specific methods that you need. Within the mixin, this follows the rules as in components.
File: #/mixins/eventable
import { mapActions } from 'vuex'
export default {
methods: {
...mapActions([])
goToEvent (event, upcoming = false) {
store.dispatch({
type: 'setEventsDay',
day: event.start_date
})
}
}
}
Usage in component:
import eventable from '#/mixins/eventable'
export default {
name: 'ComponentName',
mixins: [eventable],
methods: {
componentMethod () {
this.goToEvent()
}
}
...
Method 2: Static JavaScript files
In some cases, you might have a collection of helper functions kept in a file and want the ability to import as you need.
In your case, you seem to be using a store actions (assumed from the dispatch), hence I'll be including importing and using the store within the static JS file.
File: #/static/js/eventable.js
import store from 'path_to_store_file'
const goToEvent = () => {
store.dispatch('actionName', payload)
}
export default {
goToEvent
}
Note:
Although this is not entirely necessary, but only by declaring the imported function as a method within the component will it be bound to the component instance. This will allow you to access the function in the HTML portion.
Usage in component:
import { goToEvent } from '#/static/js/eventable.js'
export default {
name: 'ComponentName',
methods: {
// Read note before this code block
goToEvent,
componentMethod () {
// When declared as a method
this.goToEvent()
// When not declared, it can still be accessed in the js portion like this
goToEvent()
}
}
...

What's the best way to share a watched property across different components in Vue?

I have this watched property called cases:
cases: {
handler: function () {
let vc = this
if (vc.areCasesValid()) {
console.log('schema-cases#handler - casesValid', vc.cases)
vc.setApiModelFromView()
vc.$emit('valid', vc.apiModel)
return true
}
else {
console.log('template-heuristic-cases#handler - casesInvalid', vc.cases)
vc.$emit('invalid')
return false
}
},
deep: true
},
All validation steps are currently inside the areCasesValidfunction, but I want to improve the usability of the application and that process involves putting the different validation steps into different components.
Taking that into account, what's the easiest (not necessarily the most elegant) way to observe the different changes that cases goes through in different components?
If you want to keep it simple and don't want to use state management like vuex, you can use an event bus:
Your event bus:
import Vue from 'vue';
export const EventBus = new Vue();
Your component that emits the event:
<template>
<div class="pleeease-click-me" #click="emitGlobalClickEvent()"></div>
</template>
<script>
// Import the EventBus we just created.
import { EventBus } from './event-bus.js';
export default {
data() {
return {
clickCount: 0
}
},
methods: {
emitGlobalClickEvent() {
this.clickCount++;
// Send the event on a channel (i-got-clicked) with a payload (the click count.)
EventBus.$emit('i-got-clicked', this.clickCount);
}
}
}
</script>
Your component that receives the event:
// Import the EventBus.
import { EventBus } from './event-bus.js';
// Listen for the i-got-clicked event and its payload.
EventBus.$on('i-got-clicked', clickCount => {
console.log(`Oh, that's nice. It's gotten ${clickCount} clicks! :)`)
});
Full example and more explanation can be found here: https://alligator.io/vuejs/global-event-bus/

Setting up a utility class and using it within a vue component

A vue application I am working on currently has lots of code redundancies relating to date functions. In an effort to reduce these redundancies, I'd like to create a utility class as shown below, import it and set it to a Vue data property within the component, so I can call the date functions within it.
I am not certain on the best way to implement this. The current implementation results in an error saying TypeError: this.dates is undefined and my goal is not only to resolve this error but create/utilize the class in the Vue environment using best standards.
Importing utility class
import Dates from "./utility/Dates";
...
Component
const contactEditView = Vue.component('contact-edit-view', {
data() {
return {
contact: this.myContact
dates: Dates
}
},
...
Dates.js
export default {
dateSmall(date) {
return moment(date).format('L');
},
dateMedium(date) {
return moment(date).format('lll');
},
dateLarge(date) {
return moment(date).format('LLL');
}
};
View
Date of Birth: {{ dates.dateMedium(contact.dob) }}
My suggestion for this is to use a plugin option in Vue. About Vue plugin
So you will crate a new folder called services, add file yourCustomDateFormater.js:
const dateFormater = {}
dateFormater.install = function (Vue, options) {
Vue.prototype.$dateSmall = (value) => {
return moment(date).format('L')
}
Vue.prototype.$dateMedium = (value) => {
return moment(date).format('lll')
}
}
In main.js:
import YourCustomDateFormater from './services/yourCustomDateFormater'
Vue.use(YourCustomDateFormater)
And you can use it anywhere, like this:
this.$dateSmall(yourValue)
Or, if you want to use mixin. Read more about mixin
Create a new file dateFormater.js
export default {
methods: {
callMethod () {
console.log('my method')
}
}
}
Your component:
import dateFormater from '../services/dateFormater'
export default {
mixins: [dateFormater],
mounted () {
this.callMethod() // Call your function
}
}
Note: "Use global mixins sparsely and carefully, because it affects every single Vue instance created, including third party components. In most cases, you should only use it for custom option handling like demonstrated in the example above. It’s also a good idea to ship them as Plugins to avoid duplicate application." - Vue documentation
dateUtilsjs
import moment from 'moment-timezone'
function formatDateTime(date) {
return moment.utc(date).format("M/D/yyyy h:mm A")
}
export { formatDateTime }
Component JS
...
import { formatDateTime } from '../utils/dateUtils'
...
methods: {
formatDateTime,
}
Used within component
{{ formatDateTime(date) }}

Vuex how to Access state data on component mounted or created hook?

I'm trying to create a Quill.js editor instance once component is loaded using mounted() hook. However, I need to set the Quill's content using Quill.setContents() on the same mounted() hook with the data I received from vuex.store.state .
My trouble here is that the component returns empty value for the state data whenever I try to access it, irrespective of being on mounted() or created() hooks. I have tried with getters and computed properties too. Nothing seems to work.
I have included my entry.js file, concatenated all the components to make things simpler for you to help me.
Vue.component('test', {
template:
`
<div>
<ul>
<li v-for="note in this.$store.state.notes">
{{ note.title }}
</li>
</ul>
{{ localnote }}
<div id="testDiv"></div>
</div>
`,
props: ['localnote'],
data() {
return {
localScopeNote: this.localnote,
}
},
created() {
this.$store.dispatch('fetchNotes')
},
mounted() {
// Dispatch action from store
var quill = new Quill('#testDiv', {
theme: 'snow'
});
// quill.setContents(JSON.parse(this.localnote.body));
},
methods: {
setLocalCurrentNote(note) {
console.log(note.title)
return this.note = note;
}
}
});
const store = new Vuex.Store({
state: {
message: "",
notes: [],
currentNote: {}
},
mutations: {
setNotes(state,data) {
state.notes = data;
// state.currentNote = state.notes[1];
},
setCurrentNote(state,note) {
state.currentNote = note;
}
},
actions: {
fetchNotes(context) {
axios.get('http://localhost/centaur/public/api/notes?notebook_id=1')
.then( function(res) {
context.commit('setNotes', res.data);
context.commit('setCurrentNote', res.data[0]);
});
}
},
getters: {
getCurrentNote(state) {
return state.currentNote;
}
}
});
const app = new Vue({
store
}).$mount('#app');
And here is the index.html file where I'm rendering the component:
<div id="app">
<h1>Test</h1>
<test :localnote="$store.state.currentNote"></test>
</div>
Btw, I have tried the props option as last resort. However, it didn't help me in anyway. Sorry if this question is too long. Thank you for taking your time to read this. Have a nice day ;)
I copied your code and tested it ( of-course I created my own dummy notes so I could remove the get request ) and I was able to get the notes display on a page.
A couple of things that I realized from your code, you may need to add a store property as there are places in your component ( test ) where you are referencing it, yet you only define it on the 'app' component. So in this section of your code modify as shown below:
props: ['localnote'],
data() {
return {
localScopeNote: this.localnote,
store : store
}
},
The key difference is the definition of the 'store' property. Please note that, what you have done, defining a "store" property in your app component, is correct, but the very same needs to be defined in "test" component as I have shown in the above code snippet above.
Second thing is, you are using $store and I guess that gives you undefined, unless as you said, in the libraries that you included this resolves accordingly, but on my side I had to remove all references of "$store" and replace it with just "store" (without the dollar sign).
Lastly for testing purposes, I would advise you to also

Categories