Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
614 views
in Technique[技术] by (71.8m points)

vue.js - Parent variable not updated when updating trough child component

I am trying to create a few custom form fields for my page and i learned that i cannot use props to do so so i am trying to find a way to update my parent component variable when i use my child component. Whe i check the parent variable it is always empty.

Here is my component:

<template>
    <input
        v-model="value"
        :placeholder="placeHolder"
        class="form-field"
    >
</template>
<script>
export default {
    props: ['placeHolder'],
    data() {
      return {
          value: ''
      }
    },
    methods: {
        updateValue(){
            this.$emit("update-text", this.value);
        }
    },
    watch: {
        value: function(){
            this.updateValue
        }
    }
}
</script>

And this is how i use the component:

<TextField placeholder="Nome" :update-text="name = value"/>

what exactly am i doing wrong? I am using vue.js with nuxt.js

question from:https://stackoverflow.com/questions/65851125/parent-variable-not-updated-when-updating-trough-child-component

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think a simpler approach in this case might be emitting an input event from your custom text field and binding the component to the variable using v-model.

TextField.vue

<template>
    <input
        @input="$emit('input', $event.target.value)"
        :placeholder="placeHolder"
        class="form-field"
    >
</template>
<script>
export default {
    props: ['placeHolder']
}
</script>

Usage

<template>
    <TextField placeholder="Nome" v-model="name"/>
</template>

<script>
export default {
    data: () => ({
        name: '',
    }),
}
</script>

Read more about using v-model on custom components here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...