自从 vue3 [代号:海贼王] 在 2022年2月7日 成为默认版本后,vue2 将在 2023年底 彻底结束。
那么最近7月1日发布的,vue2 的最后 2.7 版本 [代号:火影忍者] 又能有什么用呢?
vue2.7正是为了解决过度问题,增加了部分vue3的写法和特性,又保留vue2原始特性。

如果 ui框架和一些三方件 还没有升级到 vue3.x , 这时可以先升级到 vue2.7,用 vue3的写法,去开发 vue2 新页面。
等到三方件和ui框架升级后,我们就可以直接去升级vue3.x,之前用vue3写法开发的页面会享受到 vue3 代理对象proxy的优势; 那么之前 vue2语法, vue3也是兼容的,只是数据响应速度和性能还是vue2的程度。
①删除根目录的 node_modules文件夹 和 package-lock.json
②打开 package.json 文件 => 修改配置如:

③修改配置后: 执行命令 npm i 下载升级后的三方件包。
① setup() 函数 和 ( 单文件组件 )
- <template>
- <div>
- <h3> {{ num }} h3>
- <button @click = "add"> 增加+1 button>
- div>
- template>
- <script>
- import { ref } from 'vue';
- export default {
- setup() {
- const num = 123;
- function add(){
- num.value++;
- }
- return { num, add };
- },
- }
- script>
- ----------------------------------------------
-
- <script setup>
- import { ref } from 'vue';
- const num = ref(18);
- function add(){
- num.value++;
- }
- script>
② 组合 API (reactive 、ref 、watch ...)
- <template>
- <div>
- <h3> {{ num }} h3>
- <button @click = "add"> 增加+1 button>
- div>
- template>
- <script setup>
- import { ref , watch } from 'vue';
- const num = ref(18);
- function add(){
- num.value++;
- }
- watch(num ,(now , old)=>{ console.log( 'num更新了=>' + num ) })
-
- script>
③ CSS v-bind (单文件组件)
- <template>
- <div>
- <div class='box'>div>
- <button @click='colorChange'>更换颜色button>
- div>
- template>
- <script setup>
- import { ref } from 'vue';
- const bool = ref(false);
- const color = ref('red');
- function colorChange(){
- bool.value = !bool.value;
- bool.value?color.value='red':color.value='blue';
- }
- script>
- <style scoped>
- .box{
- width:100px;
- height:100px;
- background:v-bind('color');
- }
- style>
④ defineComponent() 重载函数
最重要作用是:在TypeScript下,给予了组件 正确的参数类型推断 。
封装其实意义不大,如:
- <script>
- export function defineComponent(options: unknown) {
- return isFunction(options) ? { setup: options } : options
- }
- script>
⑤ 支持emits对象
主要是子组件调用父组件的方法,起到一个验证作用 =>
① 子组件 如:
- <template>
- <div>
- <button @click = "childClick"> 按钮 button>
- div>
- template>
- <script>
- export default {
- emits:{
- toFather: (bool) { retrun bool };
- //=>传入true 才会验证通过
- //toFather: null 非验证
- },
- setup(props,{emit}) {
- function childClick(){
- emit('toFather', true);
- }
- return { childClick};
- },
- }
- script>
②父组件 如:
- <template>
- <div>
- <Btn @toFather = "fun"/>
- div>
- template>
- <script>
- import Btn from './Btn.vue'
- export default {
- setup() {
- function fun(){
- console.log('被子组件 调用了!')
- }
- return { fun };
- },
- }
- script>