vue实现数据
Vue 数据绑定与状态管理
在 Vue 中,数据绑定和状态管理是核心功能,主要通过响应式系统、组件通信和状态管理库实现。
响应式数据绑定
Vue 使用 data 选项声明响应式数据,数据变更会自动触发视图更新:
export default {
data() {
return {
message: 'Hello Vue!',
count: 0
}
}
}
模板中通过双花括号或指令绑定数据:
<p>{{ message }}</p>
<button @click="count++">Count: {{ count }}</button>
计算属性与侦听器
计算属性 (computed) 适用于派生状态:

computed: {
reversedMessage() {
return this.message.split('').reverse().join('')
}
}
侦听器 (watch) 用于响应数据变化执行异步操作:
watch: {
count(newVal, oldVal) {
console.log(`Count changed from ${oldVal} to ${newVal}`)
}
}
组件间通信
父组件通过 props 传递数据:
// 子组件
props: ['title'],
// 父组件
<ChildComponent title="Data from parent" />
子组件通过 $emit 触发事件:

// 子组件
this.$emit('update', newValue)
// 父组件
<ChildComponent @update="handleUpdate" />
状态管理 (Vuex/Pinia)
对于复杂应用,推荐使用状态管理库。以 Pinia 为例:
// store/counter.js
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
actions: {
increment() {
this.count++
}
}
})
组件中使用:
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore()
// 读取
counter.count
// 修改
counter.increment()
异步数据获取
结合 async/await 获取异步数据:
data() {
return {
posts: []
}
},
async created() {
try {
this.posts = await fetch('/api/posts').then(res => res.json())
} catch (error) {
console.error('Fetch error:', error)
}
}






