myinput.vue 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. <template>
  2. <div>
  3. <!-- 能保证 v-model 可以在最底层组件使用。通过将底层的事件往上传,而不是在中间层修改 -->
  4. <input v-bind="$attrs" :value="value" v-on="inputListeners" />
  5. <!-- 这个会报错: mutate props -->
  6. <!-- <input v-model="value"> -->
  7. </div>
  8. </template>
  9. <script>
  10. export default {
  11. name: "Myinput",
  12. props: {
  13. value: {
  14. type: Number,
  15. default: 2333,
  16. },
  17. },
  18. computed: {
  19. inputListeners: function () {
  20. var vm = this;
  21. console.log(this.$listeners.input); // 从调用 <myinput @input /> 而来
  22. // `Object.assign` merges objects together to form a new object
  23. return Object.assign(
  24. {},
  25. // We add all the listeners from the parent
  26. // 不会覆盖父组件的listener。是怎么通知父组件的呢?this是谁?
  27. // 比如 <myinput @focus />, <input @focus='focus' />, 被调用时,会触发???
  28. this.$listeners,
  29. // Then we can add custom listeners or override the
  30. // behavior of some listeners.
  31. {
  32. // This ensures that the component works with v-model
  33. input: function (event) {
  34. vm.$emit("input", +event.target.value);
  35. },
  36. }
  37. );
  38. },
  39. },
  40. };
  41. </script>