带你了解Vue2和Vue3区别(四)——组件写法对照表
Vue3的选项式API setup()函数
选项式API | setup()函数 | <script setup> | |
---|---|---|---|
Props声明 | props选项 | 选项式API的props选项 | defineProps() |
访问Props | $props | setup(props){} | const props = defineProps() |
事件声明 | emits选项 | 选项式API的emits选项 | defineEmits() |
emit方法 | $emit() | setup(props,ctx) { ctx.emit() } | const emit = defineEmits() |
v-model | 子组件选项 props:[‘modelValue’], emits:[‘update:modelValue’], 然后使用$emit()抛出事件 | 同选项式API,但通过setup()函数的第二个参数的emit方法抛出事件 | const model = defineModel() |
模版引用ref | this. r e f s 对象,比如 t h i s . refs对象,比如this. refs对象,比如this.refs.name | setup() { const name = ref(null); return{name}; } | const name = ref(),引用将存储在与名字匹配的 ref 里 |
生命周期 | 比如mounted选项 | 同选项式API | 比如onMounted(() => { console.log(`omMounted`) }) |