Composition API实践
上一篇我们『纸上谈兵』了一番,但是纸上得来终觉浅,我们还需要实践,实践过了才是真正的掌握。
纸上谈兵地址:vue3新特性理论——纸上谈兵
让我们来写一段为了用API而用API的辣鸡代码:HelloWorld每秒钟变换颜色,点击则停止变换颜色。
在App.vue中,引入reactive, ref, toRefs, onMounted
API,我们将需要响应的数据写在reactive
里面或者用ref
包裹,将方法写在自定义的methods对象里,在onMounted的时候每秒执行改变颜色index的方法,stopChange里清除定时器。setup
需要返回被响应的对象。我们使用展开符展开对象的时候那些对象将不再是响应式的,此时需要使用toRefs
来将他们转为响应式。
<template>
<div id="app">
123
<HelloWorld :msg="msgg" :colorIndex="colorIndex" :onStop="stopChange"/>
div>
template>
<script>
import HelloWorld from './components/HelloWorld.vue'
import { reactive, ref, toRefs, onMounted } from 'vue'
export default {
name: 'App',
components: {
HelloWorld
},
setup(){
const state = reactive({
msgg: 'hello hahahahahahahhaha',
timer: null
})
const colorIndex = ref(1)
const methods = {
changeColor(){
if(colorIndex.value >= 4){
colorIndex.value = 1
return
}
colorIndex.value++
},
stopChange(){
clearInterval(state.timer)
}
}
onMounted(()=>{
state.timer = setInterval(()=>{
methods.changeColor()
}, 1000)
})
return {colorIndex, ...toRefs(state), ...toRefs(methods)}
}
}
script>
setup
就相当于以前的beforeCreate
和created
,以前的mounted和其他一些生命周期现在前面需要加上『on』,onMounted
。
单个响应属性我们可以使用ref来包裹声明,多个则使用reactive更为方便。
在HelloWorld.vue中:
<template>
<div :class="`hello color${colorIndex}`" @click="$emit('stop')">
<p>{{ msg }}p>
{{colorIndex}}
div>
template>
<script>
import { toRefs } from 'vue'
export default {
name: 'HelloWorld',
props: {
msg: String,
colorIndex: Number
}
}
script>
<style scoped>
.hello{
width: 100px;
height: 200px;
background-color: bisque;
}
.color1{
background-color: blueviolet;
}
.color2{
background-color: brown;
}
.color3{
background-color: coral;
}
style>
Fragment实践
新建List.vue:
<template>
<div class="list" v-for="(item,index) in dataMsg" :key="index">
hhahahha
<div v-if="item.list" class="list">
ooooooooo
<list :dataMsg="item.list"/>
div>
div>
template>
<script>
export default {
name: 'List',
props:{
dataMsg: {
type: Array
}
}
}
script>
<style scoped>
.list{
width: 200px;
height: 50px;
background-color: darkblue;
margin-top: 5px;
color: #fff;
}
style>
App.vue中引入:
<List :dataMsg="list">List>
数据:
const state = reactive({
list :[
{id: 1, name: 123},
{id: 2,name: 123},
{id: 3,name: 123},
{id: 4,name: 123},
{id: 5,name: 123},
{id: 6,name: 123, list: [
{id: 1, name: 123},
{id: 2,name: 123},
{id: 3,name: 123},
{id: 4,name: 123},
{id: 5,name: 123},
{id: 6,name: 123}
]}
]
})