vue怎么实现数据
Vue 数据绑定与状态管理方法
双向数据绑定(v-model)
在表单元素上使用 v-model 实现双向绑定,数据变更自动同步到视图:
<input v-model="message">
<p>{{ message }}</p>
data() {
return {
message: '初始值'
}
}
响应式数据声明
在 data() 中返回的对象会被 Vue 转为响应式,属性变化触发视图更新:
data() {
return {
counter: 0,
list: ['a', 'b']
}
}
计算属性(computed)
依赖其他数据动态计算的属性,具有缓存机制:
computed: {
reversedMessage() {
return this.message.split('').reverse().join('')
}
}
方法更新数据(methods)
通过方法主动修改数据,注意与计算属性的区别:

methods: {
increment() {
this.counter++
}
}
侦听器(watch)
监听特定数据变化执行异步或复杂操作:
watch: {
counter(newVal, oldVal) {
console.log(`计数器从${oldVal}变为${newVal}`)
}
}
Props 父传子通信
父组件通过属性传递数据,子组件用 props 接收:

<!-- 父组件 -->
<ChildComponent :title="parentTitle" />
<!-- 子组件 -->
<script>
export default {
props: ['title']
}
</script>
自定义事件子传父
子组件通过 $emit 触发事件传递数据:
// 子组件
this.$emit('update', newValue)
// 父组件
<ChildComponent @update="handleUpdate" />
Vuex 状态管理
复杂应用中使用集中式状态管理:
// store.js
const store = new Vuex.Store({
state: { count: 0 },
mutations: {
increment(state) {
state.count++
}
}
})
// 组件中使用
this.$store.commit('increment')
Composition API(Vue 3)
使用 ref 和 reactive 创建响应式数据:
import { ref, reactive } from 'vue'
setup() {
const count = ref(0)
const state = reactive({ items: [] })
function increment() {
count.value++
}
return { count, state, increment }
}






