目录
一、定义组件的数据
之前在2版本中都是data()中定义,现在在3版本可以在setup()中通过ref和reactive创建响应式对象,具体如下
<template> <div class="home"> <p>{{ mes }}</p> <ul> <li v-for="(i,index) in lists.list" :key="index">{{ i }}</li> </ul> </div> </template> <script> // @ is an alias to /src import {ref,reactive} from 'vue' export default { name: 'HomeView', setup(){ const mes=ref('我来啦'); const lists=reactive({ list:['我是1号','它是三号','大家是8号'] }) return { mes, lists } } } </script>
看来代码之后我们可以将ref和reactive的区别理解成ref是定义基本数据类型,reactive定义复杂数据类型,同时不要忘了将变量return出去,外部想要访问就要·return出去
二、methods中定义的方法写到setup中
在之前2版本中时间的函数我们都是写到methods中,但是在3版本中可以在setup中写,使用function定义函数的样式
<template> <div class="home"> <p>{{ mes }}</p> <button @click="handle2">我是3版本</button> </div> </template> <script> // @ is an alias to /src import {ref} from 'vue' export default { name: 'HomeView', setup(){ const mes=ref(10); function handle2(){ mes.value+=10; } return { mes, handle2 } }, } </script>
三、setup中使用props和context
2版本中可以使用this关键字获取当前组件的实例,并执行变量修改,方法调用,但是在3版本中无法使用this,但是可以通过接受setup(props,context)获取当前组件的实力和props
<template> <div class="home"> <p>{{ mes }}</p> </div> </template> <script> // @ is an alias to /src import {ref} from 'vue' export default { name: 'HomeView', props:{ mes:String }, setup(props,context){ console.log(context) const mes=props.mes; return { mes } } } </script>
四、在setup中使用生命周期
onbeforeCreate
oncreated
onbeforeMount
onmounted
onbeforeUpdate
onupdated
onbeforeUnmount
onunmount
在setup中放置的生命周期函数可以有多个
<template> <div class="home"> </div> </template> <script> // @ is an alias to /src import {onMounted} from 'vue' export default { name: 'HomeView', setup(){ onMounted(() =>{ console.log('mounted') }) } } </script>
五、provide()和inject函数的使用
Provide()和inject可以实现嵌套组件之间的数据传递,但是他们只能在setup函数中使用,父级组件使用provide()向下传递数据,子级组件使用inject()获取上层传递过来的数据,并且不限层级
//父组件App.vue
<template> <nav> <router-link to="/">Home</router-link> | <router-link to="/about">About</router-link> </nav> <router-view/> </template> <script> import {provide} from 'vue'; export default{ setup(){ provide("kk",'我是定义的值') } } </script>
//子组件Homeview.vue
<template> <div class="home"> <p>传来的值={{ a }}</p> </div> </template> <script> // @ is an alias to /src import {onMounted,inject} from 'vue' export default { name: 'HomeView', setup(){ const a=inject("kk"); return{ a } } } </script>