why isn't this child event updating state in parent (Vue) - javascript

I have a component called customize-charts that includes a Vuetify drawer:
<template>
<v-col>
<v-btn style="float: right" class="mr-4 mt-2" small #click="toggleCustomize" v-if="!open">Customize Dashboard</v-btn>
<v-navigation-drawer
v-model="open"
temporary
absolute
right
style="width: 25vw"
>
<span>draw contents</span>
<v-divider />
</v-navigation-drawer>
</v-col>
</template>
<script>
export default {
props: {
data: {
type: Array,
default () { return [] }
},
open: {
type: Boolean,
default () { return false }
}
},
data () {
return {
draggingItem: null
}
},
methods: {
toggleCustomize () {
this.$emit('open')
}
}
}
</script>
As you can see, the boolean that the drawer is listening to is called "open" and it is passed from the parent:
<customize-charts v-if="chartCards.length" :data="chartCards" :open="customizePanel" #updateorder="updateOrder" #toggleshow="toggleShow" #open="customizePanel=!customizePanel"/>
The parent also has the following:
{
data () {
return {
customizePanel: false,
}
}
}
My problem is that when the custom event open is called (#open="customizePanel=!customizePanel"), the drawer opens, but when it closes (user clicks outself of drawer) it does not set customizePanel to false. How can I make this happen?

Problem is you are using prop open with v-model. Props are designed as one way data binding only (passing data from parent to child) and you should not modify it's value in child component (if you open browser Dev Tools, I'm sure you will see nice warning from Vue explaining exactly this) as the new value will be overwritten by parent value on next re-render...
just use computed property for v-model:
computed: {
isOpen: {
get() { return this.open }, // return prop value
set() { this.$emit('open') } // emit event and change prop value in parent's event handler - new value gets propagated back to child
}
}

Related

Make a reactive component with vuejs

I need a Vue component to show some HTML content in v-data-table from Vuetify. I have seen this post Vue 2 contentEditable with v-model, and I created a similar code shown below.
My problem is the component is not reactive. When I click the "Test button", no content is updated in HtmlTextArea.
<template>
<div>
<v-btn #click="doTest()">Test Button</v-btn>
<HtmlTextArea
v-model="content"
style="max-height:50px;overflow-y: scroll;"
></HtmlTextArea>
</div>
<template>
export default {
name: "ModelosAtestados",
components: { HtmlTextArea },
data: () => ({
content: "",
}),
methods: {
doTest() {
this.content = "kjsadlkjkasfdkjdsjkl";
},
},
};
//component
<template>
<div ref="editable" contenteditable="false" v-on="listeners"></div>
</template>
<script>
export default {
name: "HtmlTextArea",
props: {
value: {
type: String,
default: "",
},
},
computed: {
listeners() {
return { ...this.$listeners, input: this.onInput };
},
},
mounted() {
this.$refs.editable.innerHTML = this.value;
},
methods: {
onInput(e) {
this.$emit("input", e.target.innerHTML);
},
},
};
</script>
This occurs because HtmlTextArea sets the div contents to its value prop only in the mounted lifecycle hook, which is not reactive.
The fix is to setup a watcher on value, so that the div contents are updated to match whenever a change occurs:
// HtmlTextArea.vue
export default {
watch: {
value: {
handler(value) {
this.$refs.editable.innerHTML = value;
}
}
}
}
demo
In the #click event binder, you have to pass a function. You passed the result of an executed function.
To make it work: #click="doTest" or #click="() => doTest()".
How to debug such problems:
Display the value you want to update on your template to check if its updated: {{content}}
Use the vue devtool extension to check the current state of your components

Vue.js Loading and hiding async component

I am making a chatbot in vue.js and I need your help. I created 2 Vue components:
ChatLoader.vue - first components that render a button to open actual webchat window
Webchat.vue - the async component that only loads when I
Click on a button to open the chat window.
So what my ChatLoader.vue is doing is setting parameter chatInitialized = true on button click. Then the chat window is opened.
In my Webchat.vue I have a close button which on click only hides the chat window (not removed from DOM) by setting showWindow = false;
Now when the chat window is hidden I again see the button to open the chat (which was there all the time only not visible because overlapped by chatwindow) but when I click on the button now I want to set showWindow = true in Webchat.vue component instead of the previous behavior, so the webchat window is shown again.
ChatLoading.vue:
<template>
<div>
<span class="open-chat" v-on:click="showChat">
<i class="icon ficon-live-chat"></i>
Virtual assistant
</span>
<Webchat v-if="chatInitialized"></Webchat>
</div>
</template>
<script>
import ChatLoading from "./ChatLoading.vue";
const Webchat = () => ({
component: import('./Webchat.vue'),
loading: ChatLoading
});
export default {
data() {
return {
chatInitialized: false
}
},
components: {
Webchat
},
methods: {
showChat() {
this.chatInitialized = true;
}
}
}
</script>
Webchat.vue:
<template>
<div class="chat-window" v-show="showWindow">
<button type="button" class="cancel icon ficon-close" v-on:click="minimize"></button>
<WebchatPlugin
>
</<WebchatPlugin>
</div>
</template>
<script>
import <WebchatPlugin{
createDirectLine,
createStore
} from "botframework-webchat/lib/index";
import {DirectLine} from "botframework-directlinejs";
export default {
data() {
return {
showWindow : true
}
},
components: <WebchatPlugin
methods: {
minimize() {
this.showWindow = false
}
},
</script>
How can I accomplish that? Thank you
If you want to toggle the child component's (<Webchat>) state showWindow from a consuming parent component, then you will have to create a method in the child component that can be invoked by the parent element.
First of all, in your Webchat component, create a new method, say maximize, that will change this.showWindow to true:
methods: {
minimize() {
this.showWindow = false;
},
maximize() {
this.showWindow = true;
}
},
Then, in your parent component, you can then:
Create a reference to your Webchat component
Use this.$ref to access the component and its inner methods, and call the maximize() method you've just created:
Example:
<template>
<div>
<span class="open-chat" v-on:click="showChat">
<i class="icon ficon-live-chat"></i>
Virtual assistant
</span>
<!-- Use `ref` attribute to create a reference to component -->
<Webchat ref="webchat" v-if="chatInitialized"></Webchat>
</div>
</template>
<script>
import ChatLoading from "./ChatLoading.vue";
const Webchat = () => ({
component: import('./Webchat.vue'),
loading: ChatLoading
});
export default {
data() {
return {
chatInitialized: false
}
},
components: {
Webchat
},
methods: {
showChat() {
this.chatInitialized = true;
// Access Webchat component's inner method
// Do this inside `this.$nextTick` to ensure it is accessible
this.$nextTick(() => {
this.$refs.webchat.maximize();
});
}
}
}
</script>

Dynamically changing props

On my app, I have multiple "upload" buttons and I want to display a spinner/loader for that specific button when a user clicks on it. After the upload is complete, I want to remove that spinner/loader.
I have the buttons nested within a component so on the file for the button, I'm receiving a prop from the parent and then storing that locally so the loader doesn't show up for all upload buttons. But when the value changes in the parent, the child is not getting the correct value of the prop.
App.vue:
<template>
<upload-button
:uploadComplete="uploadCompleteBoolean"
#startUpload="upload">
</upload-button>
</template>
<script>
data(){
return {
uploadCompleteBoolean: true
}
},
methods: {
upload(){
this.uploadCompleteBoolean = false
// do stuff to upload, then when finished,
this.uploadCompleteBoolean = true
}
</script>
Button.vue:
<template>
<button
#click="onClick">
<button>
</template>
<script>
props: {
uploadComplete: {
type: Boolean
}
data(){
return {
uploadingComplete: this.uploadComplete
}
},
methods: {
onClick(){
this.uploadingComplete = false
this.$emit('startUpload')
}
</script>
Fixed event name and prop name then it should work.
As Vue Guide: Custom EventName says, Vue recommend always use kebab-case for event names.
so you should use this.$emit('start-upload'), then in the template, uses <upload-button #start-upload="upload"> </upload-button>
As Vue Guide: Props says,
HTML attribute names are case-insensitive, so browsers will interpret
any uppercase characters as lowercase. That means when you’re using
in-DOM templates, camelCased prop names need to use their kebab-cased
(hyphen-delimited) equivalents
so change :uploadComplete="uploadCompleteBoolean" to :upload-complete="uploadCompleteBoolean"
Edit: Just noticed you mentioned data property=uploadingComplete.
It is easy fix, add one watch for props=uploadComplete.
Below is one simple demo:
Vue.config.productionTip = false
Vue.component('upload-button', {
template: `<div> <button #click="onClick">Upload for Data: {{uploadingComplete}} Props: {{uploadComplete}}</button>
</div>`,
props: {
uploadComplete: {
type: Boolean
}
},
data() {
return {
uploadingComplete: this.uploadComplete
}
},
watch: { // watch prop=uploadComplete, if change, sync to data property=uploadingComplete
uploadComplete: function (newVal) {
this.uploadingComplete = newVal
}
},
methods: {
onClick() {
this.uploadingComplete = false
this.$emit('start-upload')
}
}
})
new Vue({
el: '#app',
data() {
return {
uploadCompleteBoolean: true
}
},
methods: {
upload() {
this.uploadCompleteBoolean = false
// do stuff to upload, then when finished,
this.uploadCompleteBoolean = true
},
changeStatus() {
this.uploadCompleteBoolean = !this.uploadCompleteBoolean
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<button #click="changeStatus()">Toggle Status {{uploadCompleteBoolean}}</button>
<p>Status: {{uploadCompleteBoolean}}</p>
<upload-button :upload-complete="uploadCompleteBoolean" #start-upload="upload">
</upload-button>
</div>
The UploadButton component shouldn't have uploadingComplete as local state (data); this just complicates the component since you're trying to mix the uploadComplete prop and uploadingComplete data.
The visibility of the spinner should be driven by the parent component through the prop, the button itself should not be responsible for controlling the visibility of the spinner through local state in response to clicks of the button.
Just do something like this:
Vue.component('upload-button', {
template: '#upload-button',
props: ['uploading'],
});
new Vue({
el: '#app',
data: {
uploading1: false,
uploading2: false,
},
methods: {
upload1() {
this.uploading1 = true;
setTimeout(() => this.uploading1 = false, Math.random() * 1000);
},
upload2() {
this.uploading2 = true;
setTimeout(() => this.uploading2 = false, Math.random() * 1000);
},
},
});
<script src="https://rawgit.com/vuejs/vue/dev/dist/vue.js"></script>
<div id="app">
<upload-button :uploading="uploading1" #click="upload1">Upload 1</upload-button>
<upload-button :uploading="uploading2" #click="upload2">Upload 2</upload-button>
</div>
<template id="upload-button">
<button #click="$emit('click')">
<template v-if="uploading">Uploading...</template>
<slot v-else></slot>
</button>
</template>
Your question seems little bit ambiguë, You can use watch in that props object inside the child component like this:
watch:{
uploadComplete:{
handler(val){
//val gives you the updated value
}, deep:true
},
}
by adding deep to true it will watch for nested properties in that object, if one of properties changed you ll receive the new prop from val variable
for more information : https://v2.vuejs.org/v2/api/#vm-watch
if not what you wanted, i made a real quick example,
check it out hope this helps : https://jsfiddle.net/K_Younes/64d8mbs1/

Cannot make vue.js element-ui's dialog work while it's inside a child component

Here is the parent component:
<template lang="pug">
.wrapper
el-button(type="primary", #click="dialogAddUser = true") New User
hr
// Dialog: Add User
add-edit-user(:dialog-visible.sync="dialogAddUser")
</template>
<script>
import * as data from '#/components/partials/data'
import AddUser from './partials/AddUser'
export default {
name: 'users',
components: { AddUser },
data () {
return {
users: data.users,
dialogAddUser: false
}
}
}
</script>
Here is the child component:
<template lang="pug">
el-dialog(width="75%", title="New User", :visible.sync="dialogVisible", top="5vh")
div 'el-dialog-body' - content goes here
</template>
<script>
export default {
name: 'add-user',
props: {
dialogVisible: Boolean
}
}
</script>
I am able to open the dialog but when close the dialog using top right button inside the dialog then I am getting this error:
Avoid mutating a prop directly since the value will be overwritten
whenever the parent component re-renders. Instead, use a data or
computed property based on the prop's value. Prop being mutated:
"dialogVisible"
Later I tried to play and did something like below, but now I cannot even open the dialog:
<template lang="pug">
el-dialog(width="75%", title="New User", :visible.sync="visibleSync", top="5vh")
div 'el-dialog-body' - content goes here
</template>
<script>
export default {
name: 'add-user',
props: {
dialogVisible: Boolean
},
watch: {
visibleSync (val) {
this.$emit('update:dialogVisible', val)
}
},
data () {
return {
visibleSync: this.dialogVisible
}
}
}
</script>
If visible.sync works, the component is emitting an update:visible event.
So, to not mutate in the child and, instead, propagate the event to the parent, instead of:
:visible.sync="dialogVisible"
Do
:visible="dialogVisible", v-on:update:visible="visibleSync = $event"
Full code:
<template lang="pug">
el-dialog(width="75%", title="New User", :visible="dialogVisible", v-on:update:visible="visibleSync = $event", top="5vh")
div 'el-dialog-body' - content goes here
</template>
<script>
export default {
name: 'add-user',
props: {
dialogVisible: Boolean
},
watch: {
visibleSync (val) {
this.$emit('update:dialogVisible', val)
}
},
data () {
return {
visibleSync: this.dialogVisible
}
}
}
</script>
As another alternative, you could emit directly from the v-on listener and do without the visibleSync local property:
<template lang="pug">
el-dialog(width="75%", title="New User", :visible="dialogVisible", v-on:update:visible="$emit('update:dialogVisible', $event)", top="5vh")
div 'el-dialog-body' - content goes here
</template>
<script>
export default {
name: 'add-user',
props: {
dialogVisible: Boolean
}
}
</script>
I think a nice way to handle this is to:
Use a prop to pass the visible state from the parent to the child.
Forward el-dialog's close event from the child to the parent.
In the parent, handle the close event to set the prop to false.
Child:
<el-dialog :visible="visible" #close="$emit('close')">
export default {
props: {
visible: Boolean
},
...
Parent (assuming you store the open state in state.modalOpen):
<el-button #click="state.modalOpen = true">Open Modal</el-button>
<child-component :visible="state.modalOpen" #close="state.modalOpen = false" />

Vue.js Component rendering after prop update

In Vue.js i have a component (Answer Component) like this:
<template>
<a class="quiz-input-choice" :class="{'quiz-input-choice--selected': answer.selected}"
#click="toggleSelect()" :selected="answer.selected">
<img :src="answer.image_path"/>
<p class="quiz-input-choice__description">{{answer.title}}</p>
</a>
</template>
<script>
export default {
props: ['answer'],
methods: {
toggleSelect() {
this.$parent.$emit('answer-selected', this.answer.id);
}
}
}
</script>
If in the parent (Question Component) I update the "selected" attribute of the element, this component will not be rerendered.
export default {
props: ['question'],
components: {QuizAnswer},
created: function () {
let _self = this;
this.$on('answer-selected', id => {
let i = _self.question.answers.map(item => item.id).indexOf(id);
let answer = _self.question.answers[i];
answer.selected = !answer.selected;
});
}
}
In Vue Developer Console, i checked that Answer component data are updated, so the answer is marked as selected. Anyway, is not rendered with the "quiz-input-choice--selected" class.
If, strangely, I update from the parent other attribute of the prop (for example (answer.title), then the child component is rendered correctly with also the class "quiz-input-choice--selected".
So i guess it's a problem of detecting changes from the child.
Thank you everybody for the answers.
I discovered the problem. The "selected" attribute of the answer was not present in the initial object, so Vue cannot make reactive that attribute.
https://v2.vuejs.org/v2/guide/reactivity.html
I solved making reactive that property in the parent component.
created() {
let self = this;
this.question.answers.forEach(function (answer) {
self.$set(answer, 'selected', false);
});
},
I think you have a structural issue here. You shouldn't submit an event to your parent, since the component is supposed to be self-contained.
What you can do however is emitting an event in the child component (Answer) that will be catch in the parent (Question).
Answer.vue
<template>
<a class="quiz-input-choice" :class="{'quiz-input-choice--selected': answer.selected}"
#click="toggleSelect()" :selected="answer.selected">
<img :src="answer.image_path"/>
<p class="quiz-input-choice__description">{{answer.title}}</p>
</a>
</template>
<script>
export default {
props: ['answer'],
methods: {
toggleSelect() {
this.$emit('answer-selected');
}
}
}
</script>
Question.vue
Your template will have be catching the event like this (I don't know where your answers are so I assume that you have a answers array) :
<answer
v-for="(answer, index) in answers"
:answer="answer"
#answer-selected="answerSelected(index)"
></answer>
And your script will look like this :
export default {
props: ['question'],
components: {QuizAnswer},
data() {
return {
answers: [],
selectedAnswer: -1,
};
},
watch: {
selectedAnswer(newIndex, oldIndex) {
if (oldIndex > -1 && this.answers.length > oldIndex) {
// Reset old value
this.answers[oldIndex].selected = false;
}
if (newIndex > -1 && this.answers.length > newIndex) {
// Set new value
this.answers[newIndex].selected = true;
}
},
},
methods: {
answerSelected(index) {
this.selectedAnswer = index;
},
},
};

Categories

Resources