- 起初 Vue3.0 暴露变量必须
return
出来,template
中才能使用; - Vue3.2 中 只需要在
script
标签上加上setup
属性,组件在编译的过程中代码运行的上下文是在setup()
函数中,无需return
,template
可直接使用。 - 本文章以Vue2的角度学习Vue3的语法,让你快速理解Vue3的Composition Api
- 本文章第十四节为状态库
Pinia
的安装、使用讲解
一、文件结构
Vue2中,<template>
标签中只能有一个根元素,在Vue3中没有此限制
<template>
// ...
</template>
<script setup>
// ...
</script>
<style lang="scss" scoped>
// 支持CSS变量注入v-bind(color)
</style>
二、data
<script setup>
import {
reactive, ref, toRefs } from 'vue'
// ref声明响应式数据,用于声明基本数据类型
const name = ref('Jerry')
// 修改
name.value = 'Tom'
// reactive声明响应式数据,用于声明引用数据类型
const state = reactive({
name: 'Jerry',
sex: '男'
})
// 修改
state.name = 'Tom'
// 使用toRefs解构
const {
name, sex} = toRefs(state)
// template可直接使用{
{name}}、{
{sex}}
</script>
vue实战视频讲解:进入学习
三、method
<template>
// 调用方法
<button @click='changeName'>按钮</button>
</template>
<script setup>
import {
reactive } from 'vue'
const state = reactive({
name: 'Jery'
}) // 声明method方法
const changeName = () => {
state.name = 'Tom'
}
</script>
四、computed
<script setup>
import {
computed, ref } from 'vue'
const count = ref(1)
// 通过computed获得doubleCount
const doubleCount = computed(() => {
return count.value * 2
})
// 获取
console.log(doubleCount.value)
</script>
五、watch
<script setup>
import {
watch, reactive } from 'vue'
const state = reactive({
count: 1
})
// 声明方法
const changeCount = () => {
state.count = state.count * 2
}
// 监听count
watch(
() => state.count,
(newVal, oldVal) => {
console.log(state.count)
console.log(`watch监听变化前的数据:${
oldVal}`)
console.log(`watch监听变化后的数据:${
newVal}`)
},
{
immediate: true, // 立即执行
deep: true // 深度监听
}
)
</script>
六、props父传子
子组件
<template>
<span>{
{
props.name}}</span>
// 可省略【props.】
<span>{
{
name}}</span>
</template>
<script setup>
// import { defineProps } from 'vue'
// defineProps在<script setup>中自动可用,无需导入
// 需在.eslintrc.js文件中【globals】下配置【defineProps: true】
// 声明props
const props = defineProps({
name: {
type: String, default: ''
} })
</script>
父组件
引入子组件,组件会自动注册
<template>
<child name='Jerry'/>
</template>
<script setup>
// 引入子组件
import child from './child.vue'
</script>
七、emit子传父
子组件
<template>
<span>{
{
props.name}}</span>
// 可省略【props.】
<span>{
{
name}}</span>
<button @click='changeName'>更名</button>
</template>
<script setup>
// import { defineEmits, defineProps } from 'vue'
// defineEmits和defineProps在<script setup>中自动可用,无需导入
// 需在.eslintrc.js文件中【globals】下配置【defineEmits: true】、【defineProps: true】
// 声明props
const props = defineProps(