 vue3.0与vue3.2对比
vue3.0与vue3.2对比
  vue3.0 与 vue3.2 对比:
1)、vue3.0:
①、变量、方法必须 return 出来,才能在 template 中使用。
②、引入自定义组件时,还必须在 components 中进行注册后才能使用。
③、props 与 emit 通过 setup 函数来获取。
④、setup 函数须写在 script 标签内部,需要通过 export default 导出。
2)、vue3.2:
①、只需在 script 标签中添加 setup,变量和方法不需要 return 就能使用。
②、组件只需要引入,不用在 components 中注册就能够使用。
③、子组件中 props 通过 defineProps 来获取:
例如:
<template>
  <div>
    子组件{{name}} // 心欲无痕========
  </div>
</template>
<script setup>
  import {defineProps} from 'vue'
  defineProps({
   name:{
     type:String,
     default:'默认值'
   }
 })
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
④、子组件通过 defineEmits 来触发父组件事件或更改父组件数据
例如:
const $emits = defineEmits(['handleClick'])
$emits('handleClick')
1
2
2
⑤、defineExpose:子组件向父组件暴露方法和属性,父组件通过子组件实例进行调用。
例如:
// 父组件
<child ref="detail"></child>
const detail = ref() // 必须跟组件ref保持一致
// 父组件调用子组件属性
console.log(detail.value.str)
// 父组件调用子组件方法
detail.value.handleClick()
// 子组件
const str = "hello world!"
const handleClick = () => {
  console.log("我是子组件的方法")
}
defineExpose({
  str,
  handleClick
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
补充:
vue3.4 增加 defineModel (),以实现数据的双向绑定
<Child v-model:title="title">
<script setup>
  // 获取
  const title = defineModel('title', {
    default: 'hello'
  })
  const changeTitle = () => {
    title.value = 'hello world'
  }
</script>
<template>
  <div>
    <p>{{ title }}</p>
    <button @click="changeTitle">更改标题</button>
  </div>
</template>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
编辑  (opens new window)
  上次更新: 3/4/2025, 5:46:30 PM
