当前位置: 首页 > news >正文

【前端】一文掌握 Vue 3 指令用法(vue3 备忘清单)

文章目录

    • 入门
      • 介绍
      • 创建应用
      • 应用实例
      • 通过 CDN 使用 Vue
      • 使用 ES 模块构建版本
    • 模板语法
      • 文本插值
      • 原始 HTML
      • Attribute 绑定
      • 布尔型 Attribute
      • 动态绑定多个值
      • 使用 JavaScript 表达式
      • 仅支持表达式(例子都是无效)
      • 调用函数
      • 指令 Directives
      • 参数 Arguments
      • 绑定事件
      • 动态参数
      • 动态的事件名称
      • 修饰符 Modifiers
      • 指令语法
    • 响应式基础
      • 声明状态
      • 声明方法
      • `<script setup>` setup语法糖
      • 用 `ref()` 定义响应式变量
      • 有状态方法
      • 响应式样式
    • 响应式进阶 —— watch 和 computed
      • 监听状态
      • 立即监听状态
      • 监听多个值
      • 计算状态
    • 组件通信
      • defineProps
      • defineEmits
      • defineExpose
      • Provide / Inject
    • 路由
      • 1. 路由的基本使用
        • 开启命名空间后,组件中读取state数据
        • 开启命名空间后,组件中读取getters数据
        • 开启命名空间后,组件中调用dispatch
        • 开启命名空间后,组件中调用commit
      • 2. 路由的使用
      • 3.路由的query
        • 跳转路由并携带参数
      • 4. 命名路由
      • 5.params参数的使用
        • 1. 声明接收
        • 2. 传递
        • 3. 接收
      • 6.props的使用
      • 7. 编程式路由导航
      • 8.缓存路由组件
      • 9.新生命周期钩子
    • 路由守卫
      • 1.前置路由守卫
      • 2.后置路由守卫
      • 3.独享路由守卫
      • 4.组件内路由守卫
    • Vue 中使用 TypeScript
      • 为组件的 props 标注类型
        • Props 解构默认值
      • 为组件的 emits 标注类型
      • 为 ref() 标注类型
      • 为 reactive() 标注类型
      • 为 computed() 标注类型
      • 为事件处理函数标注类型
      • 为 provide / inject 标注类型
      • 为模板引用标注类型
      • 为组件模板引用标注类型
      • 选项式 API 为组件的 props 标注类型
      • 选项式 API 为组件的 emits 标注类型
      • 选项式 API 为计算属性标记类型
      • 选项式 API 为事件处理函数标注类型
      • 选项式 API 扩展全局属性
        • 类型扩展的位置
      • 选项式 API 扩展自定义选项
    • API 参考
      • 全局 API - 应用实例
      • 全局 API - 通用
      • 组合式 API - setup()
      • 组合式 API - 依赖注入
      • 组合式 API - 生命周期钩子
      • 组合式 API - 响应式: 工具
      • 组合式 API - 响应式: 核心
      • 选项式 API - 状态选项
      • 选项式 API - 生命周期选项
      • 选项式 API - 其他杂项
      • 选项式 API - 渲染选项
      • 选项式 API - 组件实例
      • 选项式 API - 组合选项
      • 内置内容 - 指令
      • 内置内容 - 组件
      • 内置内容 - 特殊 Attributes
      • 内置内容 - 特殊元素
      • 单文件组件 - 语法定义
      • 单文件组件 - \<script setup>
      • 单文件组件 - CSS 功能
      • 进阶 API - 渲染函数
      • 进阶 API - 服务端渲染
      • 进阶 API - TypeScript 工具类型
      • 进阶 API - 自定义渲染

渐进式 JavaScript 框架 Vue 3 备忘清单的快速参考列表,包含常用 API 和示例

参考:

  • Vue 3.x 官方文档
  • Vue Router 4.x 官方文档

入门

介绍

Vue 是一套用于构建用户界面的渐进式框架

  • Vue 3.x 官方文档 (cn.vuejs.org)
  • Vue Router 4.x 官方文档 (router.vuejs.org)
  • Vue 2 备忘清单

注意:Vue 3.x 版本对应 Vue Router 4.x 路由版本

创建应用

已安装 16.0 或更高版本的 Node.js

$ npm init vue@latest

指令将会安装并执行 create-vue,它是 Vue 官方的项目脚手架工具

✔ Project name: … <your-project-name>
✔ Add TypeScript? … No/Yes
✔ Add JSX Support? … No/Yes
✔ Add Vue Router for Single Page Application development? … No/Yes
✔ Add Pinia for state management? … No/Yes
✔ Add Vitest for Unit testing? … No/Yes
✔ Add Cypress for both Unit and End-to-End testing? … No/Yes
✔ Add ESLint for code quality? … No/Yes
✔ Add Prettier for code formatting? … No/Yes

Scaffolding project in ./<your-project-name>...
Done.

安装依赖并启动开发服务器

$ cd <your-project-name>
$ npm install
$ npm run dev

当你准备将应用发布到生产环境时,请运行:

$ npm run build

此命令会在 ./dist 文件夹中为你的应用创建一个生产环境的构建版本

应用实例

import {
    createApp, ref } from 'vue'

const app = createApp({
   
  setup() {
   
    const message = ref("Hello Vue3")
    return {
   
      message
    }
  }
})
app.mount('#app')

挂载应用

<div id="app">
  <button @click="count++">
    {
  { count }}
  </button>
</div>

通过 CDN 使用 Vue

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<div id="app">{
  { message }}</div>
<script>
  const {
      createApp, ref } = Vue
  createApp({
     
    setup() {
     
      const message = ref("Hello Vue3")
      return {
     
        message
      }
    }
  }).mount('#app')
</script>

使用 ES 模块构建版本

<div id="app">{
  { message, ref }}</div>
<script type="module">
  import {
      createApp, ref } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js'
  createApp({
     
    setup() {
     
      const message = ref("Hello Vue3")
      return {
     
        message
      }
    }
  }).mount('#app')
</script>

模板语法

文本插值

<span>Message: {
  { msg }}</span>

使用的是 Mustache 语法 (即双大括号),每次 msg 属性更改时它也会同步更新

原始 HTML

<p>Using text interpolation: {
  { rawHtml }}</p>
<p>Using v-html directive: <span v-html="rawHtml"></span></p>

双大括号{ {}}会将数据解释为纯文本,使用 v-html 指令,将插入 HTML

Attribute 绑定

<div v-bind:id="dynamicId"></div>

简写

<div :id="dynamicId"></div>

布尔型 Attribute

<button :disabled="isButtonDisabled">
  Button
</button>

动态绑定多个值

通过不带参数的 v-bind,你可以将它们绑定到单个元素上

<script setup>
  import comp from "./Comp.vue"
  import {
     ref} from "vue"
  const a = ref("hello")
  const b = ref("world")
</script>

<template>
  <comp v-bind="{a, b}"></comp>
</template>

如果你是使用的 setup 语法糖。需要使用 defineprops 声名(可以直接使用a/b

const props = defineProps({
   
  a: String,
  b: String
})

使用 JavaScript 表达式

{
  { number + 1 }}
{
  { ok ? 'YES' : 'NO' }}
{
  { message.split('').reverse().join('') }}

<div :id="`list-${id}`"></div>

仅支持表达式(例子都是无效)

<!-- 这是一个语句,而非表达式 -->
{
  { var a = 1 }}
<!-- 条件控制也不支持,请使用三元表达式 -->
{
  { if (ok) { return message } }}

调用函数

<span :title="toTitleDate(date)">
  {
  { formatDate(date) }}
</span>

指令 Directives

<p v-if="seen">Now you see me</p>

参数 Arguments

<a v-bind:href="url"> ... </a>
<!-- 简写 -->
<a :href="url"> ... </a>

绑定事件

<a v-on:click="doSomething"> ... </a>
<!-- 简写 -->
<a @click="doSomething"> ... </a>

动态参数

<a v-bind:[attributeName]="url"> ... </a>
<!-- 简写 -->
<a :[attributeName]="url"> ... </a>

这里的 attributeName 会作为一个 JS 表达式被动态执行

动态的事件名称

<a v-on:[eventName]="doSomething"> ... </a>
<!-- 简写 -->
<a @[eventName]="doSomething">

修饰符 Modifiers

<form @submit.prevent="onSubmit">
  ...
</form>

.prevent 修饰符会告知 v-on 指令对触发的事件调用 event.preventDefault()

指令语法

v-on:submit.prevent="onSubmit"
──┬─ ─┬──── ─┬─────  ─┬──────
  ┆   ┆      ┆        ╰─ Value 解释为JS表达式
  ┆   ┆      ╰─ Modifiers 由前导点表示
  ┆   ╰─ Argument 跟随冒号或速记符号
  ╰─ Name 以 v- 开头使用速记时可以省略

响应式基础

声明状态

<div>{
  { state.count }}</div>

import {
    defineComponent, reactive } from 'vue';

// `defineComponent`用于IDE推导类型
export default defineComponent({
   
  // setup 用于组合式 API 的特殊钩子函数
  setup() {
   
    const state = reactive({
    count: 0 });

    // 暴露 state 到模板
    return {
   
      state
    };
  },
});

声明方法

<button @click="increment">
  {
  { state.count }}
</button>

import {
    defineComponent, reactive } from 'vue';

export default defineComponent({
   
  setup() {
   
    const state = reactive({
    count: 0 });

    function increment() {
   
      state.count++;
    }

    // 不要忘记同时暴露 increment 函数
    return {
   
      state,
      increment
    };
  },
})

<script setup> setup语法糖

<script setup>
import {
      reactive } from 'vue';

const state = reactive({
      count: 0 })

function increment() {
     
  state.count++
}
</script>

<template>
  <button @click="increment">
    {
  { state.count }}
  </button>
</template>

setup 语法糖用于简化代码,尤其是当需要暴露的状态和方法越来越多时

ref() 定义响应式变量

reactive只能用于对象、数组和 MapSet 这样的集合类型,对 string、number 和 boolean 这样的原始类型则需要使用ref

import {
    ref } from 'vue';

const count = ref(0);

console.log(count); // { value: 0 }
console.log(count.value); // 0
count.value++;
console.log(count.value); // 1
const objectRef = ref({
    count: 0 });

// 这是响应式的替换
objectRef.value = {
    count: 1 };
const obj = {
   
  foo: ref(1),
  bar: ref(2)
};
// 该函数接收一个 ref
// 需要通过 .value 取值
// 但它会保持响应性
callSomeFunction(obj.foo);

// 仍然是响应式的
const {
    foo, bar } = obj;

在 html 模板中不需要带 .value 就可以使用

<script setup>
import {
      ref } from 'vue';

const count = ref(0);
</script>

<template>
  <div>
    {
  { count }}
  </div>
</template>

有状态方法

import {
    reactive, defineComponent, onUnmounted }

相关文章:

  • 字符串复习
  • scss报错Sass @import rules are deprecated and will be removed in Dart Sass 3.0.0
  • 如何加强 SSH 安全:内网和专用网络环境下的防护策略
  • Linux中的文件寻址
  • 脚手架 + 指令
  • 山东大学软件学院项目创新实训开发日志(4)之中医知识问答数据存储、功能结构、用户界面初步设计
  • 语义分析(编译原理)
  • Springcache+xxljob实现定时刷新缓存
  • Linux文件描述符的分配机制与重定向实现:揭开“一切皆文件”的面纱
  • 使用卷积神经网络识别MNIST数据集
  • AI与.NET技术实操系列(三):在 .NET 中使用大语言模型(LLMs)
  • YOLOSCM: 基于改进YOLO算法的车辆检测模型详解
  • [动规21] 乘积最大子数组 #medium
  • Qt使用QGraphicsView绘制线路图————附带详细实现代码
  • rk3586开发版新增系统调用(Android13)
  • Altium Designer 24 PCB 走线倒圆弧方法
  • 23 推导式
  • 计算机网络 OSI参考模型
  • 每日总结3.31
  • 【C++重点】lambda表达式是什么
  • 网站建设优化/足球比赛今日最新推荐
  • 网站建设中图片尺寸/网络培训平台
  • 计算机上网题的模拟网站怎么做/上海培训机构排名榜
  • 做水军那些网站好/黄冈seo
  • 近一周国内重大新闻/宁波seo网络推广主要作用
  • 做代练网站能备案/搜索引擎网站排名