[Vue3]语法变动

发布于:2025-05-15 ⋅ 阅读:(14) ⋅ 点赞:(0)

        Vue3的语法相对比Vue2有不少改变,这篇讲一下基础语法在Vue3里的形式。

创建Vue对象

        在脚手架项目中,index.html等资源不再编写代码,只作为一个容器。所有的页面代码都在.vue相关文件中进行编写,由main.js引入各个.vue文件渲染出页面,再注入给index.html等容器。        

        在这里我们演示一下单个index.html中创建vue对象:

        

v-model(双向数据绑定)

功能:在表单元素和组件上实现双向数据绑定,自动同步数据与视图。

基础用法

<template>
  <!-- 文本输入框 -->
  <input v-model="text" />
  <p>输入内容:{{ text }}</p>

  <!-- 复选框 -->
  <input type="checkbox" v-model="checked" />
  <p>选中状态:{{ checked }}</p>
</template>

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

         import可以换成下面的形式:

<script setup>
const text = Vue.ref('');//直接改用Vue.Xxxx 的方式
const checked = ref(false);
</script>

 修饰符

.lazy:改为监听 change 事件(输入完成时触发)

.number:自动将输入转为数字类型

.trim:自动去除首尾空格


v-bind(属性绑定)

功能:动态绑定 HTML 属性或组件 props,实现单向数据流。

<template>
  <!-- 绑定属性 -->
  <img :src="imageUrl" :alt="altText" />

  <!-- 动态属性名 -->
  <div :[dynamicAttr]="value"></div>

  <!-- 绑定对象 -->
  <button v-bind="buttonProps">按钮</button>
</template>

<script setup>
import { ref } from 'vue';
const imageUrl = ref('logo.png');
const altText = ref('网站标志');
const dynamicAttr = ref('data-id');
const buttonProps = ref({
  id: 'submit-btn',
  class: 'primary',
  disabled: false
});
</script>

v-on(事件监听)

功能:监听 DOM 事件或自定义事件。

<template>
  <!-- 基础用法 -->
  <button @click="count++">点击次数:{{ count }}</button>

  <!-- 方法处理 -->
  <button @click="handleClick('参数', $event)">带参事件</button>

  <!-- 事件修饰符 -->
  <form @submit.prevent="onSubmit">
    <input @keyup.enter="submit" />
  </form>
</template>

<script setup>
import { ref } from 'vue';
const count = ref(0);
const handleClick = (msg, event) => {
  console.log(msg, event);
};
</script>

修饰符:

.stop - 阻止冒泡

.prevent - 阻止默认行为

.once - 只触发一次

.self - 仅当事件源是元素本身时触发

条件渲染

v-if / v-else

<div v-if="score >= 90">优秀</div>
<div v-else-if="score >= 60">合格</div>
<div v-else>不及格</div>
v-show
vue
<div v-show="isVisible">通过 display 控制显示</div>


区别:

v-if:条件为假时移除 DOM 元素

v-show:始终保留 DOM,通过 CSS 控制显示

列表渲染 (v-for)

<template>
  <ul>
    <li v-for="(item, index) in items" :key="item.id">
      {{ index + 1 }}. {{ item.name }}
    </li>
  </ul>
</template>

<script setup>
const items = ref([
  { id: 1, name: '苹果' },
  { id: 2, name: '香蕉' }
]);
</script>