【问题标题】:function not updating vue property函数不更新 vue 属性
【发布时间】:2022-12-07 18:24:00
【问题描述】:

我有这个组件:

<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>

我正在使用 vue v3。每次单击按钮时,我仍然会看到文本“My prop: ?”在浏览器中。 在控制台中,每次单击按钮时,我都可以看到:“this.myprop undefined”。 我究竟做错了什么?

【问题讨论】:

  • 在我看来,道具只有在创建组件时才会达到顶峰,之后它们不再对外部产生反应。尝试将 prop 分配给带有 mounted hook 的数据部分。然后修改函数,使其改变数据值。
  • 我真的是 vue 的新手。你能分享一些线路代码或举个例子吗?
  • 最初加载组件时,您在 prop 中得到了什么?你也没有 default 道具的价值。
  • @oderfla 我添加了一个答案。希望它能按照您的期望工作。

标签: vue.js


【解决方案1】:

据我了解,您正试图在点击子组件的按钮时更新道具文本。如果是,您只需发出新文本并在父组件中更新它即可实现。

现场演示:

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-19
    • 2021-06-04
    • 2021-03-20
    • 2018-04-22
    • 1970-01-01
    • 2019-10-03
    • 1970-01-01
    • 2021-08-13
    相关资源
    最近更新 更多