Vue

Vue3常用

Vue3常用语法和方法

Posted by Starrynight on 2024-06-10
Estimated Reading Time 7 Minutes
Words 1.3k In Total
Viewed Times

Vue3常用语法和方法

Vue 3 主要引入了 Composition API,相比 Vue 2 更加灵活和高效。以下是 Vue 3 的 常用语法和方法,涵盖基本功能、生命周期、组件、路由、状态管理等核心内容。


1. Vue 3 项目初始化

(1)使用 Vue CLI

1
vue create my-vue3-app

(2)使用 Vite(推荐)

1
yarn create vite my-vue3-app --template vue

2. 创建 Vue 3 组件

Vue 3 使用 setup() 作为组件的入口点,替代 Vue 2 的 datamethods 等选项。

(1)基础组件

1
2
3
4
5
6
7
8
9
<script setup>
import { ref } from 'vue';

const message = ref('Hello Vue 3');
</script>

<template>
<p>{{ message }}</p>
</template>
  • ref():创建响应式变量,使用 .value 访问值。
  • script setup:简化 setup() 书写方式,推荐使用。

3. Vue 3 数据绑定

(1)插值 {{}}

1
2
3
<template>
<p>{{ message }}</p>
</template>

(2)属性绑定 v-bind

1
2
3
<template>
<img v-bind:src="imageUrl" />
</template>

简写

1
<img :src="imageUrl" />

(3)双向绑定 v-model

1
2
3
4
5
6
7
8
9
<template>
<input v-model="username" />
</template>

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

const username = ref('');
</script>

4. 事件处理

(1)监听事件 v-on

1
<button @click="increment">增加</button>
1
2
3
4
5
6
7
8
9
<script setup>
import { ref } from 'vue';

const count = ref(0);

const increment = () => {
count.value++;
};
</script>

(2)传递参数

1
<button @click="greet('Vue 3')">点击</button>
1
2
3
const greet = (name) => {
alert(`Hello, ${name}!`);
};

5. 条件渲染

(1)v-if

1
<p v-if="isVisible">显示的内容</p>

(2)v-else-if & v-else

1
2
3
<p v-if="status === 'success'">成功</p>
<p v-else-if="status === 'error'">错误</p>
<p v-else>未知状态</p>

(3)v-show(仅隐藏 display: none,不移除元素)

1
<p v-show="isVisible">这个元素可以显示/隐藏</p>

6. 列表渲染

(1)遍历数组 v-for

1
2
3
4
5
<ul>
<li v-for="(item, index) in items" :key="index">
{{ index }} - {{ item }}
</li>
</ul>
1
2
3
4
5
<script setup>
import { ref } from 'vue';

const items = ref(['苹果', '香蕉', '橙子']);
</script>

(2)遍历对象

1
2
3
<ul>
<li v-for="(value, key) in user" :key="key">{{ key }}: {{ value }}</li>
</ul>

7. 计算属性(computed()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<template>
<p>原始消息:{{ message }}</p>
<p>反转后:{{ reversedMessage }}</p>
</template>

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

const message = ref('Vue 3');

const reversedMessage = computed(() => {
return message.value.split('').reverse().join('');
});
</script>

8. 侦听器(watch()watchEffect()

(1)监听单个变量

1
2
3
4
5
6
7
8
9
<script setup>
import { ref, watch } from 'vue';

const count = ref(0);

watch(count, (newVal, oldVal) => {
console.log(`count 从 ${oldVal} 变为 ${newVal}`);
});
</script>

(2)watchEffect()(立即执行,自动追踪依赖)

1
2
3
4
5
6
7
8
9
<script setup>
import { ref, watchEffect } from 'vue';

const name = ref('Vue');

watchEffect(() => {
console.log(`当前 name 值:${name.value}`);
});
</script>

9. 生命周期钩子

钩子 作用
onMounted 组件挂载后
onUpdated 组件更新后
onUnmounted 组件卸载后

示例

1
2
3
4
5
6
7
8
9
10
11
<script setup>
import { onMounted, onUnmounted } from 'vue';

onMounted(() => {
console.log('组件已挂载');
});

onUnmounted(() => {
console.log('组件已卸载');
});
</script>

10. 父子组件通信

(1)父传子 props

1
2
<!-- 父组件 -->
<ChildComponent :message="parentMessage" />
1
2
3
4
5
6
7
8
<!-- 子组件 -->
<script setup>
defineProps(['message']);
</script>

<template>
<p>{{ message }}</p>
</template>

(2)子传父 emit

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- 子组件 -->
<script setup>
import { defineEmits } from 'vue';

const emit = defineEmits(['updateMessage']);

const sendMessage = () => {
emit('updateMessage', '新的消息');
};
</script>

<template>
<button @click="sendMessage">发送消息</button>
</template>
1
2
3
4
5
6
7
8
<!-- 父组件 -->
<ChildComponent @updateMessage="handleMessage" />

<script setup>
const handleMessage = (msg) => {
console.log('收到子组件消息:', msg);
};
</script>

11. 路由(Vue Router 4)

安装

1
yarn add vue-router

配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { createRouter, createWebHistory } from 'vue-router';
import Home from './Home.vue';
import About from './About.vue';

const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
];

const router = createRouter({
history: createWebHistory(),
routes
});

export default router;

12. 状态管理(Pinia)

安装

1
yarn add pinia

创建 store

1
2
3
4
5
6
7
8
9
10
11
12
import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++;
}
}
});

在组件中使用:

1
2
3
4
5
6
7
8
9
<script setup>
import { useCounterStore } from '@/stores/counter';

const store = useCounterStore();
</script>

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

Vue 3 的 Composition API 让代码更加模块化和易维护。


如果您喜欢此博客或发现它对您有用,则欢迎对此发表评论。 也欢迎您共享此博客,以便更多人可以参与。 如果博客中使用的图像侵犯了您的版权,请与作者联系以将其删除。 谢谢 !