What does v-on="..." syntax mean in VueJS? - javascript

I came across a Vuetify example for the v-dialog component which has the scoped slot called activator defined as follows:
<template v-slot:activator="{ on }">
<v-btn
color="red lighten-2"
dark
v-on="on"
>
Click Me
</v-btn>
</template>
I understand the purpose of scoped slots from VueJS docs and the concept of destructuring slot props but I don't understand what the meaning of v-on="on" is in this example. In particular what it means when the event is not specified with the v-on directive?
The VueJS docs on v-on only show its usage in combination with an event name explicitly specified (eg. v-on:click="...") but there is no explanation of just using it as v-on="...".
Can someone explain this syntax and its usage in the Vuetify example?

TLDR:
basic usage
<!-- object syntax (2.4.0+) -->
<button v-on="{ mousedown: doThis, mouseup: doThat }"></button>]
So basically #click="..." equals v-on:click="..." equals v-on="{click:...}"
TLDR:
vuetify implementation:
genActivator () {
const node = getSlot(this, 'activator', Object.assign(this.getValueProxy(), {
on: this.genActivatorListeners(),
attrs: this.genActivatorAttributes(),
})) || []
this.activatorNode = node
return node
}
Some insight:
It is useful if you want to abstract components and pass down multiple listeners at once instead of writing multiple lines of assignments.
Consider a component:
export default {
data() {
return {
on: {
click: console.log,
contextmenu: console.log
},
value: "any key value pair"
}
}
}
<template>
<div>
<slot name="activator" :on="on" :otherSlotPropName="value" >
<defaultComponent v-on="on" />
</slot>
</div>
</template>
Given the component above, you can access the slot properties and pass them into your custom component:
<ExampleComponent>
<template v-slot:activator="{ on, otherSlotPropName }">
<v-btn
color="red lighten-2"
dark
v-on="on"
>
Click Me
</v-btn>
</template>
<ExampleComponent />
Somethimes its easier to see it in plain javascript:
Comparing the component from above - with render function instead of template:
export default {
data() {
return {
on: {
click: console.log,
contextmenu: console.log
},
value: "any key value pair"
}
},
render(h){
return h('div', [
this.$scopedSlots.activator &&
this.$scopedSlots.activator({
on: this.on,
otherSlotPropName: this.value
})
|| h('defaultComponent', {
listeners: this.on
}
]
}
}
In the source:
In case of a blank v-on="eventsObject" the method bindObjectListener will be called resulting in the assignment of the events to data.on.
This happens in the createComponent scope.
Finaly the listeners are passed as VNodeComponentOptions and updated by updateListeners.
Where Vue extends - the Vuetify implementation inspected:
When taking into account that one can join and extend vue instances, one can convince himself that any component can be reduced to a more atomic version.
This is what vuetify utilizes in the e.g. v-dialog component by creating a activator mixin.
For now one can trace down the content of on mounted by the activatable:
const simplyfiedActivable = {
mounted(){
this.activatorElement = this.getActivator()
},
watch{
activatorElement(){
// if is el?
this.addActivatorEvents()
}
},
methods: {
addActivatorEvents(){
this.listeners = this.genActivatorListeners()
},
genActivatorListeners(){
return {
click: ...,
mouseenter: ...,
mouseleave: ...,
}
},
genActivator () {
const node = getSlot(this, 'activator', Object.assign(this.getValueProxy(), {
on: this.genActivatorListeners(),
attrs: this.genActivatorAttributes(),
})) || []
this.activatorNode = node
return node
},
}
}
With above snippet all there is left is to implement this into the actual component:
// vuetify usage/implemention of mixins
const baseMixins = mixins(
Activatable,
...other
)
const sympliefiedDialog = baseMixins.extend({
...options,
render(h){
const children = []
children.push(this.genActivator())
return h(root, ...options, children)
}
})

Related

Access scoped slot from component

I got this component:
<template>
<Popover v-slot="{ open }">
<PopoverButton>
{{ title }}
</PopoverButton>
<div v-if="computedOpen">
<PopoverPanel static>
<slot name="popover"></slot>
</PopoverPanel>
</div>
</Popover>
</template>
<script>
import {Popover, PopoverButton, PopoverPanel} from '#headlessui/vue'
import {computed, ref, watch} from 'vue'
import {useRoute} from 'vue-router'
export default {
name: 'DropdownMenuButton',
mixins: [slots],
props: {
name: {
type: String,
},
title: {
type: String,
default: ''
},
},
components: {
Popover,
PopoverButton,
PopoverPanel,
ChevronDownIcon,
},
setup(props) {
const isOpen = ref(null);
const route = useRoute()
watch(route, () => {
isOpen.value = false;
});
const computedOpen = computed(() => {
let open = ...? //this is missing...
return isOpen.value && open.value;
});
return {
computedOpen
}
},
}
</script>
This component makes use of headless UI's popover.
Now I'd like to close the popover once the route changes. While the route-change is being detected fine, I can not access the <Popover>'s open value in the setup() method to determine, whether computedOpen should return true or false.
My question: How can I access v-slot="{ open } in the computed value?
What you want is not possible.
Think about it:
Everything inside <Popover> element (the slot content) is compiled by Vue to a function returning the virtual DOM representation of the content
This function is passed to the Popover component as slots.default and when the Popover component is rendering, it calls that function passing the open value as an argument
So open value is Popover component's internal state and is only accessible inside the template (ie. slot render function)
So I think your best bet is throw away the computed idea and just use the open value directly in the template or use method instead, passing open as an argument
<div v-if="isOpen && open">
<PopoverPanel static>
<slot name="popover"></slot>
</PopoverPanel>
</div>
<div v-if="isPanelOpen(open)">
<PopoverPanel static>
<slot name="popover"></slot>
</PopoverPanel>
</div>

move dialog to a compontent in Vuetify

here's my code:
<v-btn #click="showDialog = true" >
<v-dialog
v-model="showDialog"
max-width="600"
>
<v-btn #click="showDialog = false">save</v-btn>
</v-dialog>
</v-btn>
I know that this is fairly simple code, but I would like to extract whole v-dialog to a component. I don't know how to manage showDialog. Should I use prop? I now I shouldn't modify prop from inside of the component. What's the other way?
You can use a function as a prop for changing value of the showDialog in the another component . ( To avoid getting error avoid mutating a prop directly )
exampleComponent.vue
<template>
<v-dialog v-model="showDialog" max-width="600">
<v-btn #click="hideDialog">save</v-btn>
</v-dialog>
</template>
<script>
export default {
props: {
showDialog : Boolean ,
hideDialog: Function,
},
};
</script>
mainFile.vue
<template>
<example :hideDialog="hideMethod" :showDialog="showDialog"></example>
</template>
<script>
export default {
data() {
return {
showDialog : false
}
},
methods: {
hideMethod() {
this.showDialog = false;
},
},
};
</script>
I've never been a fan of driving the visibility of a dialog with a reactive v-model value. Normally, dialogs need to do some amount of setup and state related things before displaying and before hiding.
So, what I do is I move showDialog to be a hidden internal value to the component itself, I put a ref= on the component, I implement an open() method on the component and call that when I want to show it.
This pattern feels more natural when a dialog is performing more complicated tasks than just showing static information.
So in your case:
<script id="myDialog" type="text/x-template">
<v-dialog
v-model="showDialog"
max-width="600"
>
<v-btn #click="save">save</v-btn>
</v-dialog>
</script>
[...]
<v-btn #click="openMyDialog">
<myDialog ref="myDialog">
</myDialog>
</v-btn>
On myDialog:
data: function () {
return {
[ other attributes ]
showDialog: false
}
},
methods: {
[ other methods ]
open: function (initializationData) {
[ initialization code ]
this.showDialog = true;
},
save: function (event) {
[ save code ]
this.showDialog = false;
}
}
On the parent component:
methods: {
[ other methods ]
openMyDialog: function (event) {
this.$refs.myDialog.open([ initialization data ]);
}
}

How to pass old value to setter if nothing is changed in computed property vuejs?

I'm learning to use Vuejs so don't mind me!
I have set getter and setter inside computed property and use it inside form with v-model. My problem is, if I change something inside the v-text-field then I can make patch request but if I don't change anything and leave it the value I got from the state then I can't make the patch request as it said the field may not be null.
How can I leave default value (value I get from state) to the v-text-field and be able to make patch request if i don't want to change anything inside the field.
my vue component.vue
<template>
<div id="update-post">
<v-dialog v-model="updatePostModal" max-width="600">
<v-card class="px-5 py-5">
<v-form ref="form" v-on:submit.prevent="update">
<v-text-field
type="text"
v-model="title" <---
label="Title"
required
></v-text-field>
</v-form>
<v-card-actions>
<v-btn color="green darken-1 white--text" #click="update">
Update
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</div>
</template>
<script>
import { getAPI } from "../axios-base";
export default {
name: "UpdatePostModal",
data() {
return {
updateTitle: null,
};
},
computed: {
title: {
get() {
var title = this.$store.state.APIData.postTitle;
return title;
},
set(value) {
this.updateTitle = value;
},
},
},
methods: {
update: function() {
var id = this.$store.state.APIData.postID;
getAPI
.patch(
`/api/posts/${id}/`,
{
title: this.updateTitle,
},
{
headers: {
Authorization: `Bearer ${this.$store.state.accessToken}`,
},
}
)
},
};
</script>
It seems like you have a few mistakes. First one, in here:
.patch(
`/api/posts/${id}/`,
{
title: this.updateTitle,
},
You are using the variable defined in data in your request. You should instead use the computed property so, it should be:
.patch(
`/api/posts/${id}/`,
{
title: this.title,
},
Next, the way you are using the state is also not right. If you are reading the computed property from the state you should always set it via the state as well. Otherwise, you'd end up with some unexpected behavior as your app grows. In order to do that you can do something like this:
get() {
// read from the state
},
set(value) {
// create an action to update the post title in the state
store.dispatch(
'updatePostTitle',
value
);
}
If you still don't want to do this, as a workaround you can address your problem like this (keeping in mind to fix the first issue mentioned above):
computed: {
title: {
get() {
return this.updateTitle || this.$store.state.APIData.postTitle;
},
set(value) {
this.updateTitle = value;
},
},
},

Vuejs: How to make this if else as Boolean?

I have a component with buttons that show some elements (v-autocomplete) when we click on them, but I should make it with a Boolean to simplify the code, how can I do that?
Because actually, it adds the index of the item in one array in showCompetence state, but I just would like a Boolean on each index Basically at the "openCompetence" function in "Methods".
import { mapGetters, mapActions } from "vuex";
export default {
name: "SkillCvCard",
data() {
return {
selectedCompetence: []
}
},
updated() {
this.addSelectSkill(this.userCompetences.competences.list);
console.log(this.selectedSkills)
},
props: {
userCompetences: {
type: Array
},
showCompetence: {
type: Array
}
},
computed: {
...mapGetters(["selectedSkills"]),
console: () => console,
},
methods: {
...mapActions(['addSelectSkill']),
openCompetence(index) {
if (this.showCompetence.includes(index)) {
console.log("close")
this.showCompetence.splice(this.showCompetence.indexOf(index), 1)
} else {
this.showCompetence.push(index)
console.log("open")
}
console.log(this.showCompetence)
}
}
about the template I will just add the minimum I hope it will be ok:
The first is where we click, to launch the "openCompetence" function.
<div v-for="(competences, index) of userCompetences.competences" :key="index">
{{ competences.category }} <v-btn #click="openCompetence(index)"> Add </v-btn>
</div>
the rest is a v-container with a v-for including multiple v-autocomplete, but the most important inside is the v-if:
<div class="skill-field" v-for="(skill, index) of userCompetences.competences" :key="index">
<template>
<v-flex md12 sm12 xs12 v-if="skill.list.length>0">
<v-autocomplete
v-if="showCompetence.includes(index)"
v-model="userCompetences.competences.list"
:items="skill.list"
chips
hide-selected
:label="skill.category"
item-text="name"
item-value="name"
multiple
>
</v-autocomplete>
</v-flex>
</template>
</div>
Normally, you would use a computed property to solve a problem like this. However, because you are inside of a v-for, a computed property is a little more difficult since you can't evaluate it in the context of each value of the v-for's index.
There are two common options:
Do exactly what you are doing. It's actually no less efficient since it will not re-evaluate unless data it depends on changes.
Add a computed called something like competencesDisplayState that returns an array of booleans that matches the ordering of the userCompetences.competences array in the v-for. Then your v-if can become something like:
v-if="competencesDisplayState[index]"
I normally just opt for the first approach as it is simpler and is easier to read and maintain.
If you want to go route 2, here's some code for the competencesDisplayState computed:
competencesDisplayState: () => {
var result = [];
for (var index=0;index < this.userCompetences.competences.length;++index) {
result(this.showCompetence.includes(index));
}
return result;
}

passing a callback function via props to child component is undefined in child vue

I have a Vue component that passes a callback function to another child component via props. However, it is the only piece that is undefined in the child.
I have created a repo for this so the files can be looked at. In the file brDialog.vue, I am passing button to the function click(), which should have access to the buttons callback that was passed within props from App.vue, however it is undefined within brDialog while the other two things passed with it are present(label and data).
I'll post the brDialog file, and will post the others if needed, but figured it would be easier to link a repo than post all the different files. I'm a bit new to Vue, so possibly something I'm missing in the documentation.
If you run the repo and click the Form Test button in the header, this is where the issue is.
brDialog.vue
<template>
<v-container>
<v-layout row wrap>
<v-flex xs12>
<v-dialog
v-model="show"
width="500"
persistent
>
<v-card>
<v-card-title> {{ title }} </v-card-title>
<slot name="content"></slot>
<v-card-actions>
<v-btn
v-for="button in buttons"
:key="button.label"
small
#click.native="click(button)"
>
{{ button.label }}
</v-btn>
<v-btn
v-if="showCloseButton"
small
#click.native="closeDialog()"
>
{{ closeButtonLabel }}
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</v-flex>
</v-layout>
</v-container>
</template>
<script>
import { props } from './props.js'
export default {
name: 'brForm',
components: {
brTextField: () => import('#/controls/brTextField/brTextField.vue'),
brTextArea: () => import('#/controls/brTextArea/brTextArea.vue'),
brSelectList: () => import('#/controls/brSelectList/brSelectList.vue')
},
props: props,
data () {
return {
}
},
methods: {
async click (button) {
const response = await button.callback(button.data)
if (response.close) {
this.closeDialog()
}
},
closeDialog () {
this.$emit('close')
}
},
computed: {
}
}
</script>
<style>
</style>
Maybe this is something I'm missing with an $emit in Vue or something, but it seems it should be working. Can someone point out why the callback is undefined after being passed to brDialog?
callback is undefined because you define your data property (App.vue from your repo) with an arrow function and loose the Vue context on this:
data: () => {
return {
testingForm: {
//...
dialog: {
props: {
buttonCallback: this.testingFormSave, //<-- here
buttons: [
{
label: 'Save',
data: {},
callback: this.testingFormSave //<-- and here
}
]
}
}
}
}
},
To fix your issue, change data: () => {...} to data () {...}

Categories

Resources