基于上篇文章 【使用vuecli 快速创建vue3项目】 的项目结构
我们在home.vue中加入如下代码
制作一个简单的计数器,有暂停,开始功能,使用vue3组合api实现,使用了setup,onMounted,ref。
可以看官方网站的案例,只是稍微修改了下,没有使用vue2的方式做。
<template>
<div class="home">
<div id="counter">Counter: {{ Counter }}</div>
<p><button type="button" @click="stop">停止</button></p>
<p><button type="button" @click="start">开始</button></p>
</div>
</template>
<script>
import { onMounted, ref } from 'vue'
export default {
name: 'Home',
setup () {
const timer = ref(null) //定义一个响应式变量 存放setInterval id
const Counter = ref(0) //定义个计数响应式变量
// 停止
const stop = () => {
clearInterval(timer.value) // ref定义的变量必须使用 变量名.value取值
}
// 开始
const start = () => {
setinterval()
}
// 自增+1
const setinterval = () => {
timer.value = setInterval(() => {
Counter.value++ //变量名.value ++
}, 1000)
}
// 进入页面启动
onMounted(start)
return { // 将变量和方法返回,这样模板中才能使用
Counter,
timer,
stop,
start
}
}
}
</script>
效果: