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
简写前
<template><Foo :count="count" @click="inc" /></template><script>// imported components are also directly usable in templateimport Foo from './Foo.vue'import { ref } from 'vue'export default{name:"componentsName",components:{Foo},props:{a:String, // 父组件传入的参数},setup(props,ctx){const count = ref(0)const inc = () => {count.value++}const aa = props.actx.emit("sonEvent",123)return {count,inc,aa,}}}</script>
简写后
<script> // 可以多个script标签混合使用export default {name:"componentsName",inheritAttrs: false, // 取消默认props继承}</script><script setup>// 导入的组件也可以直接在模板中使用,无需再用componentsimport Foo from './Foo.vue'import { ref } from 'vue'// 正常像写setup() 那样编写const count = ref(0)const inc = () => {count.value++}// 引入定义props 和 emit,也可以不用引入// import { defineProps, defineEmit } from 'vue'// 使用propsconst props = defineProps({a: String,})const aa = props.a// 使用emitconst emit = defineEmits(['sonEvent'])emit("sonEvent",123)// 暴露一些变量或者方法,见下defineExpose({aa})// 无需再return</script><template><Foo :count="count" @click="inc" /></template>
子组件实例传递问题
目前使用简写后,这个组件作为子组件,子组件的方法需要通过以下方法才能给父组件调用
父组件:
子组件:
需要通过defineExpose,来选择要暴露什么 变量 / 方法 给父组件使用
<script setup>import { ref } from 'vue'const a = 1const b = ref(2)defineExpose({a,b})</script>
