vue简单实现

Vue 简单实现示例
以下是一个使用 Vue.js 创建简单应用的示例,涵盖基本功能如数据绑定、事件处理和组件化。
基础 HTML 结构
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue Simple Demo</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
</head>
<body>
<div id="app">
{{ message }}
<button @click="reverseMessage">Reverse</button>
</div>
<script src="app.js"></script>
</body>
</html>
JavaScript 代码 (app.js)
new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
},
methods: {
reverseMessage: function() {
this.message = this.message.split('').reverse().join('');
}
}
});
组件化示例
Vue.component('todo-item', {
props: ['todo'],
template: '<li>{{ todo.text }}</li>'
});
new Vue({
el: '#app',
data: {
groceryList: [
{ id: 0, text: 'Vegetables' },
{ id: 1, text: 'Cheese' },
{ id: 2, text: 'Bread' }
]
}
});
对应 HTML
<div id="app">
<ol>
<todo-item
v-for="item in groceryList"
v-bind:todo="item"
v-bind:key="item.id">
</todo-item>
</ol>
</div>
Vue 3 组合式 API 示例
const { createApp, ref } = Vue;
createApp({
setup() {
const count = ref(0);
function increment() {
count.value++;
}
return {
count,
increment
};
}
}).mount('#app');
关键点说明
- 数据绑定:使用双大括号
{{ }}语法 - 事件处理:通过
v-on或@简写绑定方法 - 列表渲染:使用
v-for指令 - 组件通信:通过
props传递数据 - Vue 3 引入组合式 API,逻辑更灵活
这个示例展示了 Vue 的核心功能,可以根据需要扩展更复杂的功能模块。







