在该组件的其余部分找不到 Vue3 设置返回值

Vue3 setup returned value can't be found in the rest of that component

它说“这里返回的任何内容都将可用于组件的其余部分”(https://v3.vuejs.org/guide/composition-api-introduction.html#setup-component-option),但我在 c 上遇到了这个错误,这是一个在设置中返回的变量:找不到名称 'c'.ts(2304).

<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
  setup(props) {
    let c = 123;
    return { c }
  },
  methods: {
    increment() {
      c;
    }
  }
})
</script>

有什么帮助吗?

您需要在方法中使用 this 关键字访问通过 setup 方法公开的变量。

警告:

但这只是一个糟糕的方法,因为您将 composition apioptions api 混合在一起。参考this线程了解两者的区别。

Vue.createApp({
  setup(props) {
    let c = 123;
    return { c }
  },
  methods: {
    increment() {
      console.log(this.c);
    }
  }
}).mount('#app')
<script src="https://unpkg.com/vue@next"></script>
<div id="app">
  <button @click="increment">Increment</button>
</div>

使用 Composition API 实现它的正确方法:

Vue.createApp({
  setup(props) {
    const c = Vue.ref(123);
    const increment = () => c.value++;

    return {
      c,
      increment
    }
  },
}).mount('#app')
<script src="https://unpkg.com/vue@next"></script>
<div id="app">
  <span>{{ c }}</span><br/><br/>
  <button @click="increment">Increment</button>
</div>

在 vue 3 中有两种创建函数的方法。

  • 在setup方法里面添加(更好)

这是这个。不存在,所以你可以写一个简单的函数,比如

const add = () => ++c.value

这里,istance还不存在,所以你可以不用这个写c。 记得导出函数并使用 ref 创建 c 变量,否则它不会更新

  • 像您一样使用方法对象

您可以使用这种方式,但您需要使用 this. 参数,因为现在存在距离