vue简单代码实现
以下是一个基于 Vue 3 的简单代码实现示例,包含基础功能演示:
基础模板结构
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue Demo</title>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
{{ message }}
<button @click="reverseMessage">Reverse</button>
</div>
<script>
const { createApp } = Vue
createApp({
data() {
return {
message: 'Hello Vue!'
}
},
methods: {
reverseMessage() {
this.message = this.message.split('').reverse().join('')
}
}
}).mount('#app')
</script>
</body>
</html>
数据绑定示例
<div id="app">
<input v-model="inputText">
<p>You typed: {{ inputText }}</p>
</div>
<script>
createApp({
data() {
return {
inputText: ''
}
}
}).mount('#app')
</script>
条件渲染
<div id="app">
<p v-if="showText">This is visible</p>
<button @click="toggleText">Toggle</button>
</div>
<script>
createApp({
data() {
return {
showText: true
}
},
methods: {
toggleText() {
this.showText = !this.showText
}
}
}).mount('#app')
</script>
列表渲染
<div id="app">
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
<script>
createApp({
data() {
return {
items: [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Cherry' }
]
}
}
}).mount('#app')
</script>
组件示例
<div id="app">
<custom-button :text="buttonText"></custom-button>
</div>
<script>
const CustomButton = {
props: ['text'],
template: `<button>{{ text }}</button>`
}
createApp({
components: {
CustomButton
},
data() {
return {
buttonText: 'Click Me'
}
}
}).mount('#app')
</script>
以上示例展示了 Vue 的核心功能:数据绑定、事件处理、条件渲染、列表渲染和组件使用。可以根据实际需求组合这些基础功能构建更复杂的应用。







