Vuejs can vue file be regarded as json compliant object definition - javascript

I have just started vuejs and noticed that some kind of strucutre in .vue files.
export default {
data() {
return {
temp: {},
list: []
};
},
methods: {
addNew: function() {
},
entitySaved($event) {
}
}
}
Can we suppose export to be json compliant structure? If so, what is meant by data() function without it property name? Losts of such styles can also be seen in vuex.

Its not a json its just an object with functions,objects
you can make one by your self to check it like:
export default {
hey(){
return true
}
}
just import something like that and check it results

Related

How to display the getter as text in the template

I have a getter, which I would like to display in the template as text.
The data is already in the getter, checked with devtools vue chrome extension.
The data I want to get from the getter looks like this:
["appel", "banaan", "kiwi"]
My component looks like this: (the name of getter is getPlaylist)
<template>
<div>
<span>{{ showPlaylist }}</span>
</div>
<template>
<script>
import { mapGetters } from "vuex";
export default {
data() {
return {
};
},
computed: {
...mapGetters("app"["getPlaylist"]),
showPlaylist() {
this.getPlaylist;
},
},
};
</script>
How can I use this getter to show the text of the array?
Thanks in advance!
Do you want to display this ["appel", "banaan", "kiwi"] in the template
If yes, modify the code to
computed: {
...mapGetters("app"["getPlaylist"]),
showPlaylist() {
return this.getPlaylist;
},
}
Not sure what you're hoping to get with ...mapGetters("app"["getPlaylist"]), but I can't see it doing anything else other than being an undefined
"app" is a string, which doesn't behave like an object or array. the only thing available that could be accessed is string methods (ie "app"["startsWith"]("a")) or characters "app"[2])
if app is a module and getPlaylist the getter, you need to define it as:
computed: {
...mapGetters(["app/getPlaylist"]),
}
alternatively if app is another getter...
computed: {
...mapGetters(["app","getPlaylist"]),
}
or if app is a namespace
computed: {
...mapGetters("app",["getPlaylist"]),
}

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()
}
}
...

Accessing an exported components data() in Vue.js

I'm just playing around with some component instance rendering within a Vue application and I was wondering, when pushing components to an array - how do we then access the data() from that given instance of the component?
So say I have something like this in App.vue (the "Grandfather" of all of my components). I have managed to push instances of both the CodeBlock and QuoteBlock components to the pageBlocks array (i.e., my front end app appends the component where I want it to be). Here is a snippet of my App.vue file:
components: {
CodeBlock,
QuoteBlock
},
data () {
return {
pageBlocks: []
}
},
methods: {
addPageBlock (componentNomen) {
this.pageBlocks.push({ componentName: componentNomen })
},
saveDraftPage () {
for (let pageBlock of this.pageBlocks) {
console.log(pageBlock.data)
}
}
}
And here is an example of my CodeBlock data (the Quote block is "modelled" almost like for like except for a few variable name changes to distinguish it inside the component):
export default {
name: 'CodeBlock',
props: [ 'type' ],
computed: {},
data () {
return {
debug: true,
codeBlock: null,
codeBlockRows: [{
'id': 1,
'text': '$ click to edit this code block'
}],
}
},
}
I've stripped out most of this component to keep things simple.
So, my question is, if the pageBlocks array in App.vue contains instances of the above exported component...how do I access the data within?
In my naiavity I thought it would be as simple as something like this:
for (let pageBlock of this.pageBlocks) {
console.log(pageBlock.data);
}
But, alas, no luck yet...any tips?

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) }}

Vue.js event bus

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

Categories