vue2.0与3.0对比以及vue3.0 API入门

9,258 阅读3分钟

Vue3.0介绍

就在昨天尤雨溪发布了VUE3.0 Beta版本。接下来会结合vue2.0和3.0的异同点进行介绍


一、入手第一步

(注意:在使用vue3.0的时候,最好将你的vue脚手架工具升级到最新的cli 4.x,我在cli3.x的上执行vue add vue-next会报错。 【升级脚手架步骤】:npm install -g @vue/cli 安装完毕以后 运行vue -V查看版本号)

1.首先利用cli4脚手架工具对项目进行初始化,为了将2个vue版本进行对比我初始化了2个项目,分别给文件夹命名为vue2.0和vue3.0,为了方便演示,配置方面我就选择了Babel。

初始化完成以后,进入到根路径下的package.json文件里,因为目前cli4.x构建的项目仍然是使用vue2.0的版本

我们现在可以在命令行工具里输入 vue add vue-next 指令将目前项目的vue版本升级到3.0 beta版本,当配置出现以下内容就说明安装成功了


二、升级到vue 3.0的变化

首先我们先打开main.js文件,会发现它与过去的版本发生了一些变化:

//vue3.0
import { createApp } from 'vue';
import App from './App.vue'
createApp(App).mount('#app')

//vue2.0
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
  render: h => h(App),
}).$mount('#app')

通过上述的代码我们会发现3.0比2.0的要精简了许多,同时还引入了一个新的函数名createApp,会把容器挂载到它上面来。


三、进入正题

接下来我会从以下几个属性及常用的方法,将2.0和3.0进行一些对比:

  • Data
  • Method
  • LifeCycle
  • Computed
  • Components
  • Props
  • Emit

1.Data:

3.0当中已经不再去使用这种方式去初始化内容了
export default {
  data(){
    return{

    }
  },
  mounted(){
      
  },
  methods:{
      
  },
  computed:{
      
  }
},
///////////////////////
取而代之是使用以下的方式去初始化数据:
<template>
  <div class="hello">
    123
  </div>
  <div>{{name.name}}</div>
</template>
import {reactive} from 'vue' 
export default {
 setup(){
   const name = reactive({
     name:'hello 番茄'
   })
   return {name}
 }  
}

tip:在新版当中setup等效于之前2.0版本当中的beforeCreate,和created,它是在组件初始化的时候执行,甚至是比created更早执行。值得注意的是,在3.0当中如果你要想使用setup里的数据,你需要将用到值return出来,返回出来的值在模板当中都是可以使用的。

假设如果你不return出来,而直接去使用的话浏览器是会提醒你:

runtime-core.esm-bundler.js?5c40:37 [Vue warn]: Property "name" was accessed during render but is not defined on instance. 
  at <Anonymous>  
  at <Anonymous> (Root)

这个也是3.0当中需要注意的地方。细心的朋友应该已经发现,我在模板里放入2个子节点,其实这个在2.0里是不被允许的,这也是3.0的一项小的改变 reactive是3.0提供的一个数据响应的方式,它主要是对对象进行数据响应,接下来会介绍另一种数据响应的方式ref。


2.Method

<template>
  <div class="hello">
    <div>{{name.name}}</div>
    <div>{{count}}</div>
    <button @click="increamt">button</button>
  </div>
  
</template>

<script>
import {reactive,ref} from 'vue'
export default {
 setup(){
   const name = reactive({
     name:'王'
   })
   const count=ref(0)
   const increamt=()=>{
     count.value++
   }
   return {name,count,increamt}
 }  
}

在介绍Method的代码中,我引用了vue提供的ref新函数,它的作用是用来创建一个引用值,它主要是对String,Number,Boolean这类普通值的数据响应作引用。也许有人会问,为什么不直接给count赋值,而是采用ref(0)这样的方式来创建呢,按我的理解就是,如果直接给count赋值就是等于把这个值直接抛出去了,就很难在找到它,而采用ref这种方法等于你在向外抛出去值的是同时,你还在它身上牵了一根绳子,方便去追踪它。 需要注意的时,在ref的函数中,如何你要去改变或者去引用它的值,ref的这个方法提供了一个value的返回值,对值进行操作。


3.LifeCycle(Hooks) 3.0当中的生命周期与2.0的生命周期出现了很大的不同:

  • beforeCreate -> 请使用 setup()

  • created -> 请使用 setup()

  • beforeMount -> onBeforeMount

  • mounted -> onMounted

  • beforeUpdate -> onBeforeUpdate

  • updated -> onUpdated

  • beforeDestroy -> onBeforeUnmount

  • destroyed -> onUnmounted

  • errorCaptured -> onErrorCaptured

如果要想在页面中使用生命周期函数的,根据以往2.0的操作是直接在页面中写入生命周期,而现在是需要去引用的,这就是为什么3.0能够将代码压缩到更低的原因。

import {reactive, ref, onMounted} from 'vue'
export default {
 setup(){
   const name = reactive({
     name:'王'
   })
   const count=ref(0)
   const increamt=()=>{
     count.value++
   }
   onMounted(()=>{
     console.log('123')
   })
   return {name,count,increamt}
 }  

举个栗子:

过去的2.0就像是我们在餐厅吃饭,是等菜上齐了我们再开始吃饭,有的时候菜点多了就会造成不必要的浪费。而现在的3.0更像是在吃自助餐,你吃多少就拿多少,就不会造成浪费。


4.computed

<template>
  <div class="hello">
    <div>{{name.name}}</div>
    <div>{{count}}</div>
    <div>计算属性{{computeCount}}</div>
    <button @click="increamt">button</button>

  </div>
  
</template>

<script>
import {reactive, ref, onMounted,computed} from 'vue'
export default {
 setup(){
   const name = reactive({
     name:'王'
   })
   const count=ref(0)
   const increamt=()=>{
     count.value++
   }
   const computeCount=computed(()=>count.value*10)//使用computed记得需要引入,这也是刚接触3.0容易忘记的事情
   onMounted(()=>{
     console.log('123')
   })
   return {name,count,increamt,computeCount}
 }  
}
</script>

四、我们再来讨论一下vue3.0组件的使用方法

在开始介绍3.0组件的用法之前,我们可以先回顾一下2.0使用组件的方式。 在2.0当中,哪个页面需要使用组件就在哪个页面里引入该组件,同时在页面注册这个组件。在传递参数时,父组件传递参数给子组件,子组件就会接收父组件传递过来的参数。

举个栗子:

父组件
<template>
  <div id="app">
    <HelloWorld msg="Welcome to Your Vue.js App" @childclick="parentClick"/>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  components: {
    HelloWorld
  },
  methods:{
      parentClick(e){
          console.log(e)// '123'
      }
  }
}
</script>

子组件
<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data(){
    return{
      
    }
  },
  method:{
    handleClick(){
      this.$emit('childclick','123')
    }
  }
}
</script>

以上是最常见的父子组件之间的调用,但是在vue3.0中就存在差异。

废话不多说,先上DJ(代码)! 先上DJ(代码)!!

父组件

<template>
  <div class="hello">
    <div>123</div>
  <NewComp :name="name" @childClick="parentClick"/>
  </div>
  
</template>

<script>
import {reactive} from 'vue'
import NewComp from './newComp.vue'
export default {
  components:{
    NewComp
  },
 setup(){
   const name=ref('hello 番茄')
   const parentClick=(e)=>{
     console.log(e)
     console.log('123')
   }
   return {name,parentClick}
 }  
}
</script>

子组件

<template>
    <div>
        <button @click="handleClick">{{props.name}}</button>
    </div>
</template>

<script>
export default {
    props:{
        name:String
    }
    setup(props,{emit} ){
        const handleClick=()=>{
            console.log(props)//proxy{name:'hello 番茄'}
            emit('childClick','hello')
        }
        return {
            props,
            handleClick
        }
    }
}
</script>

通过上面的vue3.0父子组件之间的调用,我们不难发现,父组件当中在调用子组件时,基本与2.0相同,而在子组件当中,要想获取到父组件传递过来的参数,我们是直接在setup()中直接获取到props值和emit事件。这是因为setup为我们提供了props以及context这两个属性,而在context中又包含了emit等事件。 或许有人看到这里会问,为什么不用this.$emit的方法来向外触发子组件事件呢? 因为在3.0当中已经不在使用this关键词 当你在setup()里打印this关键词,会发现输出为undefined。

五、vue3.0中的逻辑复用

在vue2.0当中,如果我们想要复用逻辑,通常都是采用mixins来导入需要的函数方法,当是使用这种方法有很多的缺点,例如:

变量冲突:当使用的mixins过多时,难免会出现变量名冲突的问题。

举个栗子:

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <button @click="hello">按钮</button>
  </div>
</template>

<script>
import useResize from '../libs/size.js'
export default {
  mixins:[useResize],
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data(){
    return{

    }
  },
  methods:{
  }
}
</script>

mixins组件

export default {
    data() {
        return {
            msg: "width"
        }
    },
    methods: {
        hello() {
            console.log("hello")
        }
    },
    mounted() {
        console.log(this.msg)
        
    }
}

这里就出现了变量名重复的问题

而在vue3.0当中是如何解决的呢?再举个栗子:

<template>
  <div class="hello">
    <h1>{{ name }}</h1>
    <h1>{{obj.tall}}</h1>
    <button @click="onClick">Boom</button>
    <h1>{{num}}</h1>
    <h1>{{changeCount}}</h1>
    <button @click="incream"></button>
    <h1>{{WidthResize}}</h1>
  </div>
</template>

<script>
import { ref, reactive, computed } from "vue";
import  {useResize}  from '../libs/size.js'//导入用于逻辑复用的文件
export default {
  setup(){
    //ref => 普通型数据的引用 String,Number,Boolean
    const name=ref('hello,番茄')
    const num=ref(0)
    //reactive => 对象数据的引用
    const obj=reactive({
      tall:'180'
    })
    const onClick=()=>{
      obj.tall="200",
      name.value="该吃饭了"
    }
    const incream=()=>{
      num.value++
    }
    const changeCount=computed(()=>
      num.value*2)
    const { width:WidthResize } = useResize()//利用es6语法的解构,将需要用到的属性名或者方法结构出来
    //如果遇到变量名重复的情况,可以在解构值的后面加上自定义的属性名,如WidthResize
    return{
      name,
      obj,
      num,
      WidthResize,//把用到的变量名返回出来
      onClick,
      changeCount,
      incream
    }
  }
}
</script>

vue3.0复用的逻辑文件

import { ref, onMounted, onUnmounted } from 'vue'
export function useResize(){
    const width=ref('width')
    const height=ref('Height')
    const update=()=>{
        width.value='hello Width'
        height.value='hello Height'
    }
    onMounted(()=>{
        window.addEventListener('resize',update)
    })
    onUnmounted(()=>{
        window.removeEventListener('resize',update)
    })
    return {
        width,height
    }
}

数据来源不是很清晰:当代码量过多的时候,要想去溯源变量的来源,很难去方便的追溯到它。

再再再举个栗子

在vue2.0当中,对于代码量过多的时候,要想找到一个变量的来源是很困难的,甚至会遇到这个变量是来源于其它文件。就如上面所讲到的mixins方法,如果你之前没用过mixins,你甚至都不知道这个hello方法是从哪里来的,这个样很容易给代码的阅读造成很大的困扰。

而在vue3.0中就优化了这个问题,因为在3.0当中,所有的变量都是局部变量,这样方便在查找变量或者方法名的时候,更为简便。

六、总结

vue3.0 vs vue2.0

  • 变化
  • 对普通类型的值(String,Number,Boolean)的引用以及赋值采用ref(),改变赋值的引用采用 xx.value='xxx'
  • 对对象类型的赋值采用reactive({})
  • 生命周期的变化
  • 方法、计算属性以及监听属性的变化
  • 优化:
  • 逻辑复用的提升,解决了变量名冲突以及溯源困难的问题