vue 简单实现
Vue 简单实现示例
以下是一个基础的 Vue.js 实现示例,包含数据绑定、事件处理和组件化功能。
初始化 Vue 项目
通过 Vue CLI 快速创建项目:
npm install -g @vue/cli
vue create my-project
cd my-project
npm run serve
基础模板结构
在 src/App.vue 文件中:
<template>
<div id="app">
<h1>{{ title }}</h1>
<button @click="changeTitle">修改标题</button>
<ChildComponent :message="childMessage" />
</div>
</template>
<script>
import ChildComponent from './components/ChildComponent.vue';
export default {
name: 'App',
components: {
ChildComponent
},
data() {
return {
title: 'Vue 示例',
childMessage: '来自父组件的消息'
};
},
methods: {
changeTitle() {
this.title = '标题已更新';
}
}
};
</script>
<style>
#app {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 20px;
}
</style>
子组件实现
创建 src/components/ChildComponent.vue:
<template>
<div class="child">
<p>{{ message }}</p>
<p>计数: {{ count }}</p>
<button @click="increment">增加</button>
</div>
</template>
<script>
export default {
props: ['message'],
data() {
return {
count: 0
};
},
methods: {
increment() {
this.count++;
}
}
};
</script>
<style scoped>
.child {
margin: 20px;
padding: 10px;
border: 1px solid #ddd;
}
</style>
核心功能说明
- 数据绑定:使用双大括号
{{ }}语法实现文本插值 - 事件处理:通过
@click等指令绑定 DOM 事件 - 组件通信:使用
props实现父向子传值 - 状态管理:组件内部通过
data()维护局部状态
运行效果
- 页面显示初始标题和子组件内容
- 点击按钮可修改标题文字
- 子组件中的计数器可独立操作
可选扩展
- 添加 Vue Router 实现页面导航
- 集成 Vuex 进行全局状态管理
- 使用 Axios 添加 HTTP 请求功能







