Hi I am trying to implement a treeview. I have a component for it which is hierarchical. The problem I am facing is that emit is not working inside tree component. Please help me out. here is my code...
TreeItem.vue
<template>
<div :style="{ marginLeft: depth * 20 'px' }">
<span v-if="type == 'country'">
<button @click="addState()">
Add State
</button>
</span>
<TreeItem
v-if="expanded"
v-for="child in node.children"
:key="child.name"
:node="child"
:depth="depth 1"
/>
</div></template>
<script>
export default {
name: "TreeItem",
props: {
node: Object,
depth: {
type: Number,
default: 0,
},
emits: ["add-state"],
},
data() {
return {
expanded: false,
};
},
methods: {
addState() {
console.log("Adding State"); //Prints this message to console
this.$emit("add-state");
},
},
};
</script>
AddressManager.vue
Inside template:
<div>
<tree-item :node="treedata" @add-state="addState"></tree-item>
</div>
Inside Methods:
addState() {
console.log("State will be added"); //Never prints this message
},
We need to emit on button click. But the emit is not working.
CodePudding user response:
So I have figured out the problem... We need to replace this.$emit()
with this.$parent.$emit()
Here is the change-
addState() {
console.log("Adding State"); //Prints this message to console
this.$parent.$emit("add-state");
},
Hopefully this resolved my issue.
CodePudding user response:
You can use v-on="$listeners" to pass emits on levels above within the depths https://v2.vuejs.org/v2/guide/components-custom-events.html#Binding-Native-Events-to-Components it would just forward them to the parent.
However in nested scenarios it is more convenient using store (vuex) and assign a property then watch property changes from wherever you would like to notice its change. If you use vuex: https://vuex.vuejs.org/api/#watch store properties can be watched.