vue简单代码实现
以下是一个基于 Vue 3 的简单代码实现示例,包含基础功能演示:
基础模板结构
<!DOCTYPE html>
<html>
<head>
<title>Vue Demo</title>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<h1>{{ message }}</h1>
<button @click="increment">Count: {{ count }}</button>
<input v-model="inputText" placeholder="Type something">
<p>Input content: {{ inputText }}</p>
</div>
<script>
const { createApp, ref } = Vue
createApp({
setup() {
const message = ref('Hello Vue!')
const count = ref(0)
const inputText = ref('')
function increment() {
count.value++
}
return {
message,
count,
inputText,
increment
}
}
}).mount('#app')
</script>
</body>
</html>
组件化示例
创建可复用的组件:
<div id="app">
<custom-button :count="count" @click="handleClick" />
</div>
<script>
const { createApp, ref } = Vue
const CustomButton = {
props: ['count'],
template: `
<button @click="$emit('click')">
Clicked {{ count }} times
</button>
`
}
createApp({
components: {
CustomButton
},
setup() {
const count = ref(0)
function handleClick() {
count.value++
}
return { count, handleClick }
}
}).mount('#app')
</script>
生命周期钩子
展示主要生命周期方法的使用:
createApp({
setup() {
onMounted(() => {
console.log('Component mounted')
})
onUpdated(() => {
console.log('Component updated')
})
onUnmounted(() => {
console.log('Component unmounted')
})
}
})
计算属性
实现自动计算的值:
const { createApp, ref, computed } = Vue
createApp({
setup() {
const firstName = ref('John')
const lastName = ref('Doe')
const fullName = computed(() => {
return `${firstName.value} ${lastName.value}`
})
return { firstName, lastName, fullName }
}
})
这些示例涵盖了 Vue 的核心功能:数据绑定、事件处理、组件通信、生命周期管理和计算属性。可以根据实际需求组合使用这些特性构建更复杂的应用。






