https://v3.cn.vuejs.org/api/sfc-script-setup.html#%E5%8D%95%E6%96%87%E4%BB%B6%E7%BB%84%E4%BB%B6-script-setup

简写前

  1. <template>
  2. <Foo :count="count" @click="inc" />
  3. </template>
  4. <script>
  5. // imported components are also directly usable in template
  6. import Foo from './Foo.vue'
  7. import { ref } from 'vue'
  8. export default{
  9. name:"componentsName",
  10. components:{
  11. Foo
  12. },
  13. props:{
  14. a:String, // 父组件传入的参数
  15. },
  16. setup(props,ctx){
  17. const count = ref(0)
  18. const inc = () => {
  19. count.value++
  20. }
  21. const aa = props.a
  22. ctx.emit("sonEvent",123)
  23. return {
  24. count,
  25. inc,
  26. aa,
  27. }
  28. }
  29. }
  30. </script>

简写后

  1. <script> // 可以多个script标签混合使用
  2. export default {
  3. name:"componentsName",
  4. inheritAttrs: false, // 取消默认props继承
  5. }
  6. </script>
  7. <script setup>
  8. // 导入的组件也可以直接在模板中使用,无需再用components
  9. import Foo from './Foo.vue'
  10. import { ref } from 'vue'
  11. // 正常像写setup() 那样编写
  12. const count = ref(0)
  13. const inc = () => {
  14. count.value++
  15. }
  16. // 引入定义props 和 emit,也可以不用引入
  17. // import { defineProps, defineEmit } from 'vue'
  18. // 使用props
  19. const props = defineProps({
  20. a: String,
  21. })
  22. const aa = props.a
  23. // 使用emit
  24. const emit = defineEmits(['sonEvent'])
  25. emit("sonEvent",123)
  26. // 暴露一些变量或者方法,见下
  27. defineExpose({
  28. aa
  29. })
  30. // 无需再return
  31. </script>
  32. <template>
  33. <Foo :count="count" @click="inc" />
  34. </template>

子组件实例传递问题

目前使用简写后,这个组件作为子组件,子组件的方法需要通过以下方法才能给父组件调用

父组件:
image.png

子组件:
需要通过defineExpose,来选择要暴露什么 变量 / 方法 给父组件使用

  1. <script setup>
  2. import { ref } from 'vue'
  3. const a = 1
  4. const b = ref(2)
  5. defineExpose({
  6. a,
  7. b
  8. })
  9. </script>