代码:
<template>
<div class="nihao">{{title}}</div>
<button @click="count++">count的值:{{ count}}</button> <br/><br/>
<button @click="changeTitle">改变标题</button>
</template>
<script setup>
import { ref } from 'vue';
let title = ref('世界')
let count = ref(0)
function changeTitle(){
title.value = 'vue3,你好'
console.log(title)
}
</script>
<style scoped>
.nihao{
background-color: bisque;
height: 50px;
}
</style>
说明:
- 本文代码为子组件中的代码
- 使用了组件式api进行编写
- 使用了setup语法糖,即在script标签里加上setup标识,简化了setup函数和return的操作
- 使用了事件响应click
- 在事件中调用变量并改变变量的值需要使用.value
- vue3的新版本内置了vue调试工具,也可在Chrome中安装vue调试插件(无法使用谷歌商店,可以在“极简插件”官网下载)
- 组件文件名命名推荐采用首字母大写的方式(小写也可以运行,但是不规范)
- 使用ref函数需要先import导入,即import {ref} from 'vue'
- style标签中添加‘scoped’,代表该段css只对本文件生效
- 如需使用typescript,需要在script标签中声明“lang='ts'”
- 也可以在script中重新给组件命名,如果集成在scirpt标签中需要安装setup插件,插件名“vite-plugin-vue-setup-extend”,如果只使用文件名当做组件名则不需要安装,安装该插件之后需要在vite.config.ts中进行配置