5

我用vue ui(typescript、babel、linter)创建了一个入门项目。一切正常,但我不太明白如何使Composition APIsetup方法工作。它根本没有被调用(日志输出为空)这是我卡住的地方。

  • Vue:3.0.0- rc.10

  • Vue-cli:4.5.4

    <script lang="ts">
     import { Options, Vue } from 'vue-class-component'
     import HelloWorld from './components/HelloWorld.vue'
    
     @Options({
       components: {
         HelloWorld
       },
       setup () {
         console.log('SETUP HERE')
       }
     })
     export default class App extends Vue {
       setup () {
         console.log('SETUP THERE')
       }
     }
     </script>
    
4

2 回答 2

4

您应该从中导入setupvue-class-component然后像这样使用它:

<template>
  <div>Count: {{ counter.count }}</div>
  <button @click="counter.increment()">+</button>
</template>

<script lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Vue, setup } from 'vue-class-component'

function useCounter () {
  const count = ref(0)

  function increment () {
    count.value++
  }

  onMounted(() => {
    console.log('onMounted')
  })

  return {
    count,
    increment
  }
}

export default class Counter extends Vue {
  counter = setup(() => useCounter())
}
</script>

有关更多详细信息,请检查此问题

于 2020-09-06T22:59:31.567 回答
1

我有同样的问题,它是由扩展子组件引起的。如果您扩展组件,则永远不会调用组合 API(设置方法)。虽然在两个组件中都调用了选项 API生命周期挂钩。

// child.js

<script>
import { onMounted } from "vue";

export default {
  name: "ChildComponent",
  setup() {
    console.log('Child - setup()');
    onMounted(() => {
      console.log('Child - mounted (composition API)');
    })
  },
  mounted() {
    console.log('Child - mounted (option API)');
  }
}
</script>
// parent.js

<script>
import ChildComponent from "./child.js";
import { onMounted } from "vue";

export default {
  name: "ParentComponent",
  extends: ChildComponent,
  setup() {
    console.log('Parent - setup()');
    onMounted(() => {
      console.log('Parent - mounted (composition API)');
    })
  },
  mounted() {
    console.log('Parent - mounted (option API)');
  }
}
</script>

输出

Parent - setup()
Parent - mounted (composition API)
Child - mounted (option API)
Parent - mounted (option API)
于 2021-06-08T11:15:15.260 回答