对比两个示例代码,很容易看出写法的改变:Vue 3 引入了 setup 函数,用于组件的逻辑和响应式数据的设置
一、Vue2
Vue2Component.vue
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 
 | <template><div>
 <h1>{{ title }}</h1>
 <button @click="increment">{{ count }}</button>
 </div>
 </template>
 
 <script>
 export default {
 data() {
 return {
 title: 'Vue 2 Component',
 count: 0
 };
 },
 methods: {
 increment() {
 this.count++;
 }
 }
 };
 </script>
 
 | 
调用Vue2Component.vue
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 
 | <template><div>
 <vue2-component></vue2-component>
 </div>
 </template>
 
 <script>
 import Vue2Component from './Vue2Component.vue';
 
 export default {
 components: {
 Vue2Component
 }
 };
 </script>
 
 | 
二、Vue3
2.1. 传统方式
Vue3Component.vue
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 
 | <template><div>
 <h1>{{ title }}</h1>
 <button @click="increment">{{ count }}</button>
 </div>
 </template>
 
 <script>
 import { ref } from 'vue';
 
 export default {
 setup() {
 const title = 'Vue 3 Component';
 const count = ref(0);
 
 const increment = () => {
 count.value++;
 };
 
 return {
 title,
 count,
 increment
 };
 }
 };
 </script>
 
 | 
调用Vue3Component.vue
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 
 | <template><div>
 <Vue3Component></Vue3Component>
 </div>
 </template>
 
 <script>
 import Vue3Component from './Vue3Component.vue';
 
 export default {
 components: {
 Vue3Component
 }
 };
 </script>
 
 | 
2.2. Setup语法糖简化代码
 注意:在使用 <script setup> 时,确保你的开发环境已经升级到 Vue 3,并且相关的构建工具和插件也支持 Vue 3 的语法。
Vue3Component.vue
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 
 | <template><div>
 <h1>{{ title }}</h1>
 <button @click="increment">{{ count }}</button>
 </div>
 </template>
 
 <script setup>
 import { ref } from 'vue';
 
 props: {
 initialCount: {
 type: Number,
 default: 0
 }
 };
 
 const title = 'Vue 3 Component';
 const count = ref(props.initialCount);
 
 const increment = () => {
 count.value++;
 };
 </script>
 
 | 
调用Vue3Component.vue
| 12
 3
 4
 5
 6
 7
 8
 9
 
 | <template><div>
 <Vue3Component :initialCount="5"></Vue3Component>
 </div>
 </template>
 
 <script>
 import Vue3Component from './Vue3Component.vue';
 </script>
 
 | 
请注意,使用 <script setup> 时,不再需要显式导入和注册组件,因为逻辑和模板已经绑定在一起,并且组件的导出部分被隐式处理。
在上面的示例中,我们可以看到一些更新:
- Vue 3 引入了 setup 函数,用于组件的逻辑和响应式数据的设置。在 setup 函数中,我们使用了 ref 来创建响应式数据,并在返回的对象中将数据和方法暴露给模板使用。
- 在 Vue 2 中,我们使用 data 选项来定义组件的数据,而在 Vue 3 中,我们在 setup 函数中使用变量和函数来代替。
- 在 Vue 3 中,我们使用 ref 来创建响应式数据,并通过 .value 来访问和修改数据的值。
- 在 Vue 3 中,我们使用 import 来引入需要的模块,如 ref。这是因为 Vue 3 使用了 ES 模块的方式进行模块化开发。