【问题标题】:cant set property of undefined vuejs 3无法设置未定义的vuejs 3的属性
【发布时间】:2021-06-30 03:14:54
【问题描述】:

在我的Something.vue

<template>
<p>{{ codes }}</p>
</template>

export default {
  data() {
    return {
      codes: 'test'
    }
  },
  name: 'Functions',
  props: {
    msg: String
  },
  setup() {
  this.codes = 'does it work?';
}
</script>

<style>
</style>

我为什么会遇到这个问题?

Uncaught TypeError: Cannot set property 'codes' of undefined

【问题讨论】:

  • 您没有打开 &lt;script&gt; 标记,并且您在代码末尾缺少一个右括号。也许是红鲱鱼?

标签: vue.js vuejs3


【解决方案1】:

vue3,你可以这样定义变量:

import { ref } from "vue";
export default {
  name: 'Functions',
  props: {
    msg: String
  },
  setup() {
    let codes = ref('does it work?');
    
    return { codes }
  }
</script>

你可以在你的 Vue 组件中使用codes

因为,在setup 方法中,不能使用this 关键字。它的执行早于其他生命周期函数

如果要更改codes,可以在setupmethods中定义一个函数,如下所示:

setup() {
  let codes = ref("does it work?");

  function onChangeCodes() {
    codes.value = "changed!";
  }

  return { codes, onChangeCodes };
}

然后,您可以在模板中使用此功能:

<template>
  <div>{{ codes }}</div>
  <button @click="onChangeCodes">change</button>
</template>

【讨论】:

    【解决方案2】:

    执行setup时,组件实例尚未创建, 换句话说,当 setup() 执行时,您无法访问“代码”。 可以查看文档here

    【讨论】:

      猜你喜欢
      • 2020-09-19
      • 2021-11-27
      • 2022-10-30
      • 2023-02-10
      • 2015-12-07
      • 2013-05-28
      • 2016-02-23
      • 2011-11-20
      相关资源
      最近更新 更多