MVVM框架
MVVM是 Model-View-ViewModel 的简写,设计思想就是关注model数据的变化,让MVVM模型自动取更新DOM。
了解MVVM之前,先看一下MVC(Model-View-Contorller)
- Model负责保存业务数据
- View负责将Model中的数据显示在视图上
- Contorller负责业务逻辑,根据用户行为改变model中的数据
相比于MVC模型的各个模块紧密连接,MVVM中 的View层和Model层并没有直接联系。而是将ViewModel作为桥梁,通过数据的双向绑定实现View层和Model层连接。
vue如何实现双向数据绑定
一、v-model
<div id="app">
<input type="text" v-model="message">
<div>{{message}}</div>
</div>
<script>
const { createApp, ref, nextTick } = Vue
const App = createApp({
setup() {
const message = ref("你好");
return {
message,
}
}
})
App.mount("#app")
</script>
二、父子组件数据绑定(自定义组件)
- 父组件
<template>
<div>
<ChildProps :msg="msg" @changeMsg="change" />
</div>
</template>
<script setup lang="ts">
import { reactive, ref } from "vue";
import ChildProps from "@/views/components/ChildProps/index.vue";
const msg = ref("你好");
function change(v: string) {
msg.value = v;
}
</script>
- 子组件
<template>
<div>
<input type="text" v-model="props.msg" @input="newValue($event.target.value)">
</div>
</template>
<script setup lang="ts">
import { reactive, ref} from 'vue'
const props = defineProps(['msg',])
// 组合式API自定义事件
const emits = defineEmits(['changeMsg'])
const newValue = (v)=>{
emits("changeMsg",v)
}
</script>