表单中的v-model

image.png
查看 https://www.yuque.com/yejielin/mypn47/xe1ml9#ts34D

组件中的v-model

image.png

相当于给这个组件一个message的属性,这个属性如果有变化,就向父组件传回来

使用

父组件APP:

  1. <template>
  2. <div>
  3. <!-- 表单上使用 -->
  4. <!-- <input v-model="message">
  5. <input :value="message" @input="message = $event.target.value"> -->
  6. <!-- 组件上使用v-model -->
  7. <hy-input v-model="message"></hy-input>
  8. <!-- 相当于-->
  9. <!-- <hy-input :modelValue="message" @update:model-value="message = $event"></hy-input> -->
  10. <h2>{{message}}</h2>
  11. </div>
  12. </template>
  13. <script>
  14. import HyInput from './HyInput.vue';
  15. export default {
  16. components: {
  17. HyInput
  18. },
  19. data() {
  20. return {
  21. message: "Hello World",
  22. }
  23. }
  24. }
  25. </script>
  26. <style scoped>
  27. </style>

子组件 HyInput

  1. <template>
  2. <div>
  3. <!-- 1.默认绑定和事件处理 -->
  4. <!-- <button @click="btnClick">hyinput按钮</button>
  5. <h2>HyInput的message: {{modelValue}}</h2> -->
  6. <!-- 2.通过input -->
  7. <input :value="modelValue" @input="btnClick">
  8. <!-- 3.绑定到props中是不对的,这样双向绑定不了,不要修改props的值 -->
  9. <!-- <input v-model="modelValue"> -->
  10. </div>
  11. </template>
  12. <script>
  13. export default {
  14. props: {
  15. modelValue: String
  16. },
  17. emits: ["update:modelValue"], // 定义emits事件
  18. methods: {
  19. btnClick(event) {
  20. this.$emit("update:modelValue", event.target.value); // 变化时传到父组件
  21. }
  22. }
  23. }
  24. </script>
  25. <style scoped>
  26. </style>

绑定多个v-model

image.png

image.png
父组件app

  1. <template>
  2. <div>
  3. <!-- 绑定两个v-model -->
  4. <hy-input v-model="message" v-model:title="title"></hy-input>
  5. <h2>{{message}}</h2>
  6. <h2>{{title}}</h2>
  7. </div>
  8. </template>
  9. <script>
  10. import HyInput from './HyInput.vue';
  11. export default {
  12. components: {
  13. HyInput
  14. },
  15. data() {
  16. return {
  17. message: "Hello World",
  18. title: "哈哈哈"
  19. }
  20. }
  21. }
  22. </script>
  23. <style scoped>
  24. </style>

子组件

  1. <template>
  2. <div>
  3. <input v-model="value">
  4. <input v-model="why">
  5. </div>
  6. </template>
  7. <script>
  8. export default {
  9. props: {
  10. modelValue: String,
  11. title: String
  12. },
  13. emits: ["update:modelValue", "update:title"],
  14. computed: {
  15. value: {
  16. set(value) {
  17. this.$emit("update:modelValue", value);
  18. },
  19. get() {
  20. return this.modelValue;
  21. }
  22. },
  23. why: {
  24. set(why) {
  25. this.$emit("update:title", why);
  26. },
  27. get() {
  28. return this.title;
  29. }
  30. }
  31. }
  32. }
  33. </script>
  34. <style scoped>
  35. </style>