0

I have this component:

<template>
  <div class="hello">
    <div>
      My prop: {{ myprop }}?
    </div>
    <div>
      <button class="fas fa-lock-open lock" @click="changeText()">Click</button>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  name: 'StartPage',
  props: {
    myprop: {
      type: String
    }
  },
  model: {
    prop: 'myprop',
    event: 'click'
  },
  methods: {
    changeText () {
      this.$emit('click', 'sometext')
      console.log('this.myprop', this.myprop)
    }
  }
})
</script>

Im using vue v3. Everytime I click on the button, I still see the text "My prop: ?" in the browser. And in the console I can see: "this.myprop undefined" every time I click on the button. What am I doing wrong?

4
  • It seems to me that props are peaked only when the component is created, after that they are no longer reactive from the outside. Try assigning prop to data section with mounted hook. Then modify function so it will change the data value. Commented Dec 6, 2022 at 14:15
  • I am really new to vue. Could you please share some line code or give an example? Commented Dec 6, 2022 at 14:36
  • what are you getting in prop when component is initially loaded? also you don't have default value for prop. Commented Dec 6, 2022 at 15:09
  • @oderfla I added an answer. Hope it will work as per your expectation. Commented Dec 7, 2022 at 10:18

1 Answer 1

1

As per my understanding, You are trying to update the prop text on click of button from the child component. If Yes, you can achieve it simply by emitting a new text and updating that in the parent component.

Live Demo :

const ShowPropText = {
  template: `<div class="hello">
               <div>
                 My prop: {{ myprop }}
               </div>
               <div>
                 <button class="fas fa-lock-open lock" @click="changeText()">Click</button>
               </div>
             </div>`,
  props: ['myprop'],
  methods: {
    changeText() {
      this.$emit('click-event', 'sometext')
    }
  }
}

const app = Vue.createApp({
  components: {
    'show-prop-text': ShowPropText
  },
  data() {
    return {
        text: 'This is default text'
    }
  },
  methods: {
    methodCall(e) {
        this.text = e;
    }
  }
})

app.mount('#app')
<script src="https://cdn.jsdelivr.net/npm/vue@next"></script>
<div id="app">
  <show-prop-text :myprop="text" @click-event="methodCall"></show-prop-text>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.