vue实现代码
以下是Vue实现常见功能的代码示例,涵盖基础语法、组件通信、状态管理等核心内容:
基础模板语法
<template>
<div>
<h1>{{ message }}</h1>
<button @click="increment">Count: {{ count }}</button>
<input v-model="inputText" placeholder="Type something">
</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello Vue!',
count: 0,
inputText: ''
}
},
methods: {
increment() {
this.count++
}
}
}
</script>
组件通信(Props & Emit)
父组件:
<template>
<ChildComponent
:title="parentTitle"
@update-title="handleUpdate"
/>
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
components: { ChildComponent },
data() {
return {
parentTitle: 'Initial Title'
}
},
methods: {
handleUpdate(newTitle) {
this.parentTitle = newTitle
}
}
}
</script>
子组件:
<template>
<div>
<h2>{{ title }}</h2>
<button @click="changeTitle">Change Title</button>
</div>
</template>
<script>
export default {
props: ['title'],
methods: {
changeTitle() {
this.$emit('update-title', 'New Title')
}
}
}
</script>
Vuex状态管理
store.js:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
counter: 0
},
mutations: {
increment(state) {
state.counter++
}
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
},
getters: {
doubleCounter(state) {
return state.counter * 2
}
}
})
组件中使用:
<template>
<div>
<p>Count: {{ $store.state.counter }}</p>
<p>Double: {{ $store.getters.doubleCounter }}</p>
<button @click="$store.commit('increment')">Increment</button>
<button @click="$store.dispatch('incrementAsync')">Async Increment</button>
</div>
</template>
组合式API(Vue 3)
<template>
<div>
<h1>{{ title }}</h1>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { ref, computed, onMounted } from 'vue'
export default {
setup() {
const count = ref(0)
const title = computed(() => `Count is ${count.value}`)
function increment() {
count.value++
}
onMounted(() => {
console.log('Component mounted')
})
return {
count,
title,
increment
}
}
}
</script>
路由配置
router.js:
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import About from './views/About.vue'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/about',
name: 'about',
component: About
}
]
})
导航使用:
<template>
<div>
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
<router-view></router-view>
</div>
</template>
这些示例涵盖了Vue开发中的核心概念,可根据实际需求进行组合和扩展。







