Vue 3 提供了多种方式来构建用户界面,包括选项式 API 和 Composition API。下面我将详细介绍 Vue 3 的基本使用和语法,主要集中在选项式 API 上,因为这对于初学者来说更容易上手。
1. 创建 Vue 项目
如果你还没有一个 Vue 项目,可以参考之前提到的方法使用 Vue CLI 创建一个新的项目:
vue create my-vue-app
选择默认配置或根据需要手动选择特性。然后进入项目目录并启动开发服务器:
cd my-vue-app
npm run serve
2. 基本结构
典型的 Vue 项目结构如下:
-
public/:存放静态资源。 -
src/:源代码目录。
assets/:放置图片等静态资源。components/:存放可复用的组件。App.vue:根组件。main.js:入口文件,负责初始化应用。
3. 单文件组件 (SFC)
在 Vue 中,单文件组件(Single File Component, SFC)是一种特殊的文件格式 .vue,它允许在一个文件中定义模板、脚本和样式。
示例:HelloWorld.vue
<template>
<div class="hello">
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
}
}
</script>
<style scoped>
.hello {
color: #42b983;
}
</style>
这里,<template> 标签定义了 HTML 模板,<script> 标签包含了 JavaScript 逻辑,而 <style> 标签则用于定义样式。scoped 属性确保样式只应用于当前组件。
4. 数据绑定
文本插值
使用双大括号 {{ }} 进行文本插值。
<span>Message: {{ message }}</span>
v-bind 绑定属性
使用 v-bind 或其简写 : 来动态设置元素的属性。
<img :src="imageSrc" alt="Image">
v-model 双向数据绑定
对于表单输入元素,v-model 实现双向数据绑定。
<input v-model="inputValue" type="text">
<p>你输入的是: {{ inputValue }}</p>
5. 事件处理
使用 v-on 或其简写 @ 来监听 DOM 事件,并调用方法。
<button @click="handleClick">点击我</button>
在 <script> 部分定义方法:
methods: {
handleClick() {
alert('按钮被点击了!');
}
}
6. 条件渲染与列表渲染
- v-if 和 v-show 用于条件性地显示元素。
- v-for 用于循环渲染列表。
示例:
<ul>
<li v-for="(item, index) in items" :key="index">{{ item.text }}</li>
</ul>
在 <script> 中定义数据:
data() {
return {
items: [
{ text: 'Item 1' },
{ text: 'Item 2' },
{ text: 'Item 3' }
]
};
}
7. 计算属性与侦听器
- 计算属性:通过
computed定义,基于依赖进行缓存。 - 侦听器:通过
watch监听数据变化并执行函数。
示例:
export default {
data() {
return {
firstName: 'John',
lastName: 'Doe'
};
},
computed: {
fullName() {
return `${this.firstName} ${this.lastName}`;
}
},
watch: {
fullName(newVal, oldVal) {
console.log(`fullName changed from ${oldVal} to ${newVal}`);
}
}
};
8. 组件通信
- Props:父组件向子组件传递数据。
- Events:子组件向父组件发送消息。
- Provide/Inject:祖先组件向后代组件提供数据。
示例:
父组件 ParentComponent.vue
<template>
<ChildComponent :message="parentMessage" @childEvent="handleChildEvent" />
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
parentMessage: 'Hello from parent'
};
},
methods: {
handleChildEvent(message) {
console.log('Received from child:', message);
}
}
};
</script>
子组件 ChildComponent.vue
<template>
<div>
<p>{{ message }}</p>
<button @click="sendToParent">Send to Parent</button>
</div>
</template>
<script>
export default {
props: ['message'],
methods: {
sendToParent() {
this.$emit('childEvent', 'Hello from child');
}
}
};
</script>
9. 路由
对于单页应用(SPA),你需要使用 vue-router 来管理不同页面之间的导航。
安装 vue-router:
npm install vue-router@next
配置路由:
创建 router/index.js 文件:
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
import About from '../views/About.vue';
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
];
const router = createRouter({
history: createWebHistory(),
routes
});
export default router;
在 main.js 中引入并使用路由器:
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
const app = createApp(App);
app.use(router);
app.mount('#app');
1619

被折叠的 条评论
为什么被折叠?



