vue 简单实现
Vue 简单实现示例
以下是一个使用 Vue.js 的简单实现示例,包含基础数据绑定、事件处理和组件化功能。

基础 HTML 结构
<!DOCTYPE html>
<html>
<head>
<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 }}
</div>
</body>
</html>
初始化 Vue 实例
new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
})
数据绑定与事件处理
双向数据绑定
<div id="app">
<input v-model="message">
<p>{{ message }}</p>
</div>
事件处理
<div id="app">
<button v-on:click="reverseMessage">Reverse Message</button>
<p>{{ message }}</p>
</div>
new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
},
methods: {
reverseMessage: function() {
this.message = this.message.split('').reverse().join('')
}
}
})
组件化实现
注册全局组件
Vue.component('todo-item', {
template: '<li>This is a todo item</li>'
})
使用组件
<div id="app">
<ol>
<todo-item></todo-item>
</ol>
</div>
带 props 的组件
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' }
]
}
})
<div id="app">
<ol>
<todo-item
v-for="item in groceryList"
v-bind:todo="item"
v-bind:key="item.id"
></todo-item>
</ol>
</div>
计算属性和侦听器
计算属性
new Vue({
el: '#app',
data: {
firstName: 'John',
lastName: 'Doe'
},
computed: {
fullName: function() {
return this.firstName + ' ' + this.lastName
}
}
})
侦听器
new Vue({
el: '#app',
data: {
question: '',
answer: ''
},
watch: {
question: function(newQuestion) {
this.answer = 'Waiting for you to stop typing...'
this.getAnswer()
}
},
methods: {
getAnswer: function() {
// 实际应用中这里可能是API调用
this.answer = 'You asked: ' + this.question
}
}
})
生命周期钩子示例
new Vue({
el: '#app',
data: {
message: 'Hello'
},
created: function() {
console.log('Instance created')
},
mounted: function() {
console.log('Instance mounted')
},
updated: function() {
console.log('Instance updated')
}
})
以上示例展示了 Vue.js 的核心功能实现,包括数据绑定、事件处理、组件化和生命周期管理等基础用法。






