Vue3 的核心语法

Vue3 的核心语法,这是前端开发中非常实用的技能!我会从基础到核心特性,用通俗易懂的方式带你掌握 Vue3 的关键语法,每个知识点都配有可直接运行的代码示例。

Vue3 核心语法详解

一、环境准备与项目创建

首先需要确保你已经安装了 Node.js(建议 v14.18+),然后通过以下命令创建 Vue3 项目:

# 安装Vue CLI(如果未安装)
npm install -g @vue/cli

# 创建Vue3项目
vue create vue3-demo

# 选择Default (Vue 3) 或手动选择特性

二、组件的基本结构

Vue3 组件有两种写法:选项式 API(Options API)(类似 Vue2,易上手)和组合式 API(Composition API)(Vue3 推荐,更灵活)。

1. 选项式 API(适合新手入门)
<!-- HelloWorld.vue -->
<template>
  <!-- 模板语法 -->
  <div class="hello">
    <h1>{{ msg }}</h1>
    <button @click="changeMsg">修改消息</button>
  </div>
</template>

<script>
// 选项式API:通过配置对象定义组件
export default {
  // 组件名称
  name: 'HelloWorld',
  // 接收父组件传递的 props
  props: {
    msg: {
      type: String,
      required: true,
      default: 'Hello Vue3'
    }
  },
  // 响应式数据
  data() {
    return {
      count: 0
    }
  },
  // 计算属性
  computed: {
    doubleCount() {
      return this.count * 2
    }
  },
  // 方法
  methods: {
    changeMsg() {
      this.msg = 'Vue3 选项式API 真好用!'
      this.count++
    }
  },
  // 生命周期钩子
  mounted() {
    console.log('组件挂载完成')
  }
}
</script>

<style scoped>
/* scoped 表示样式仅作用于当前组件 */
.hello {
  text-align: center;
  padding: 20px;
}
</style>
2. 组合式 API(Vue3 推荐,<script setup>语法糖)

这是 Vue3 最常用的写法,代码更简洁,逻辑复用更方便:

<!-- HelloWorld.vue -->
<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <p>计数:{{ count }}</p>
    <p>计数翻倍:{{ doubleCount }}</p>
    <button @click="changeMsg">修改消息</button>
  </div>
</template>

<!-- setup 语法糖:无需导出,直接编写逻辑 -->
<script setup>
// 1. 导入需要的API
import { ref, computed, onMounted } from 'vue'

// 2. 接收props(defineProps是setup语法糖内置函数)
const props = defineProps({
  msg: {
    type: String,
    required: true,
    default: 'Hello Vue3'
  }
})

// 3. 响应式数据:ref用于基本类型(String/Number/Boolean)
const count = ref(0)

// 4. 计算属性
const doubleCount = computed(() => {
  return count.value * 2 // ref类型需要通过.value访问
})

// 5. 方法
const changeMsg = () => {
  // props是只读的,如需修改需通过emit通知父组件
  emit('update:msg', 'Vue3 组合式API 真强大!')
  count.value++ // 修改ref值
}

// 6. 自定义事件(defineEmits是setup语法糖内置函数)
const emit = defineEmits(['update:msg'])

// 7. 生命周期钩子
onMounted(() => {
  console.log('组件挂载完成')
})
</script>

<style scoped>
.hello {
  text-align: center;
  padding: 20px;
}
</style>

三、核心语法要点解析

1. 响应式系统(最核心)

Vue3 的响应式系统基于 ES6 Proxy,比 Vue2 的 Object.defineProperty 更强大。

API用途示例
ref基本类型响应式(String/Number/Boolean)const count = ref(0)
reactive对象 / 数组响应式const user = reactive({ name: '张三' })
toRefs将 reactive 对象转为 ref 对象(解构不丢失响应式)const { name } = toRefs(user)

示例代码

<script setup>
import { ref, reactive, toRefs } from 'vue'

// 基本类型响应式
const age = ref(18)
age.value = 20 // 修改时需要.value

// 对象响应式
const user = reactive({
  name: '张三',
  address: {
    city: '北京'
  }
})
user.name = '李四' // 直接修改,无需.value
user.address.city = '上海' // 深层对象也支持响应式

// 解构不丢失响应式
const { name, address } = toRefs(user)
name.value = '王五' // 仍为响应式
</script>
2. 模板语法(与 Vue2 类似,新增特性)
<template>
  <!-- 文本插值 -->
  <p>{{ name }}</p>

  <!-- 指令 -->
  <div v-if="isShow">显示内容</div>
  <div v-else>隐藏内容</div>

  <!-- 循环 -->
  <ul>
    <li v-for="(item, index) in list" :key="index">
      {{ index }}: {{ item }}
    </li>
  </ul>

  <!-- 绑定属性(: 是v-bind的简写) -->
  <img :src="imgUrl" :alt="imgAlt">

  <!-- 绑定事件(@ 是v-on的简写) -->
  <button @click="handleClick">点击</button>
  <button @click="handleClick(123)">传参点击</button>

  <!-- 双向绑定(v-model) -->
  <input v-model="username" placeholder="请输入用户名">

  <!-- Vue3新增:v-model修饰符 -->
  <input v-model.trim="username" placeholder="自动去除空格">
  <input v-model.number="age" placeholder="只允许输入数字">
</template>
3. 生命周期钩子(Vue3 变更)

Vue3 的生命周期钩子与 Vue2 对应关系:

Vue2Vue3(组合式 API)用途
beforeCreate-(setup 中直接执行)组件创建前
created-(setup 中直接执行)组件创建后
beforeMountonBeforeMount挂载前
mountedonMounted挂载后
beforeUpdateonBeforeUpdate更新前
updatedonUpdated更新后
beforeDestroyonBeforeUnmount卸载前
destroyedonUnmounted卸载后

使用示例

<script setup>
import { onMounted, onUpdated, onUnmounted } from 'vue'

onMounted(() => {
  console.log('组件挂载完成,可操作DOM')
})

onUpdated(() => {
  console.log('组件数据更新完成')
})

onUnmounted(() => {
  console.log('组件卸载,清理定时器/事件监听等')
})
</script>
4. 组件通信(常用方式)
(1)父传子:props
<!-- 父组件 Parent.vue -->
<template>
  <Child :name="parentName" :age="18" @child-click="handleChildClick" />
</template>

<script setup>
import Child from './Child.vue'
import { ref } from 'vue'

const parentName = ref('父组件传递的名称')

const handleChildClick = (data) => {
  console.log('接收子组件事件:', data)
}
</script>
<!-- 子组件 Child.vue -->
<template>
  <div>
    <p>接收父组件数据:{{ name }}, {{ age }}</p>
    <button @click="emit('child-click', '子组件数据')">向父组件传值</button>
  </div>
</template>

<script setup>
// 接收props
const props = defineProps({
  name: String,
  age: Number
})

// 触发事件
const emit = defineEmits(['child-click'])
</script>
(2)子传父:emit(如上例)
(3)全局状态管理:Pinia(Vue3 替代 Vuex)
# 安装Pinia
npm install pinia
// src/store/index.js
import { createPinia } from 'pinia'
export const pinia = createPinia()
// src/store/user.js
import { defineStore } from 'pinia'

// 定义并导出store
export const useUserStore = defineStore('user', {
  // 状态(类似Vuex的state)
  state: () => ({
    username: '张三',
    age: 18
  }),
  // 计算属性(类似Vuex的getters)
  getters: {
    fullInfo() {
      return `${this.username}, ${this.age}`
    }
  },
  // 方法(类似Vuex的mutations+actions,可直接写异步)
  actions: {
    updateName(newName) {
      this.username = newName
    },
    // 异步操作
    async fetchUserInfo() {
      // 模拟接口请求
      const res = await fetch('/api/user')
      const data = await res.json()
      this.username = data.name
      this.age = data.age
    }
  }
})
<!-- 组件中使用 -->
<script setup>
import { useUserStore } from '@/store/user'

// 获取store实例
const userStore = useUserStore()

// 访问状态
console.log(userStore.username)
console.log(userStore.fullInfo)

// 调用方法
userStore.updateName('李四')
userStore.fetchUserInfo()

// 直接修改状态(Pinia支持,无需mutation)
userStore.age = 20
</script>

四、Vue3 新增特性

1. Teleport(传送门)

将组件内容渲染到指定 DOM 节点,常用于弹窗、通知等:

<template>
  <teleport to="body">
    <div class="modal" v-if="isShow">
      这是一个弹窗(渲染到body下)
      <button @click="isShow = false">关闭</button>
    </div>
  </teleport>
</template>

<script setup>
import { ref } from 'vue'
const isShow = ref(false)
</script>

<style>
.modal {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 20px;
  border: 1px solid #ccc;
}
</style>
2. Suspense(异步组件加载)

用于等待异步组件或异步操作完成后再渲染:

<template>
  <Suspense>
    <!-- 异步组件 -->
    <template #default>
      <AsyncComponent />
    </template>
    <!-- 加载中状态 -->
    <template #fallback>
      <div>加载中...</div>
    </template>
  </Suspense>
</template>

<script setup>
// 动态导入异步组件
const AsyncComponent = defineAsyncComponent(() => import('./AsyncComponent.vue'))
</script>

总结

Vue3 的核心语法重点掌握以下几点:

  1. 组合式 API<script setup> 语法糖 + ref/reactive 响应式数据
  2. 生命周期钩子onMounted/onUpdated/onUnmounted 等常用钩子
  3. 组件通信:props(父传子)、emit(子传父)、Pinia(全局状态)
  4. 模板语法:与 Vue2 兼容,新增 v-model 修饰符等实用特性
  5. 新增特性:Teleport(弹窗)、Suspense(异步加载)提升开发效率

建议你先从选项式 API 入手熟悉 Vue3 的基本用法,再逐步过渡到组合式 API(推荐)。实际开发中,<script setup> + Pinia + 组件通信是最常用的技术组合,多写示例代码就能快速掌握!

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

涔溪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值