下面是一个简单的例子 来说说明一下 组件使用数据绑定
App.vue
<template>
<div class="container">
<globai-header :user="userData"></globai-header>
<!-- <column-list :list="testData"></column-list> -->
<form class="form-horizontal my-2">
<div class="form-group my-2">
<validate-input v-model="emailValue"></validate-input>
{{emailValue}}
</div>
</form>
</div>
</template>
<script lang="ts">
import { defineComponent, reactive, ref } from "vue";
import "bootstrap/dist/css/bootstrap.min.css";
import ValidateInput, { RulesProp } from "./components/ValidateInput.vue";
export default defineComponent({
name: "App",
components: {
ValidateInput,
},
setup() {
const emailValue = ref('zhangsan')
return {
emailValue
};
},
});
</script>
**ValidateInput.vue**
```javascript
<template>
<form class="form-horizontal my-2">
<div class="form-group my-2">
<label for="inputEmail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10 my-2">
<input
type="email"
class="form-control"
:class="{ 'is-invalid': inputRef.error }"
id="inputEmail"
:value="inputRef.val"
@blur="validateInput"
placeholder="Email"
@input="updateValue"
/>
<span class="form-text my-2 invalid-feeback" v-if="inputRef.error">
{{ inputRef.message }}
</span>
</div>
</div>
</form>
</template>
<script lang="ts">
import { defineComponent, PropType, reactive } from "vue";
export type RulesProp = RuleProp[];
export default defineComponent({
name: "ValidateInput",
props: {
emailValue: String,
},
setup(props: any, context: any) {
const updateValue=(e:KeyboardEvent)=>{
const targetValue = (e.target as HTMLInputElement).value
inputRef.val = targetValue
// 发送一个事件 名成为update:modelValue
context.emit('update:modelValue',targetValue)
}
return {
updateValue
};
},
});
</script>```
即可完成简单的组件双向绑定