对于vue中v-model的理解以及model的使用

396 阅读1分钟

v-model的语法糖的等价写法

父组件

<template>
  <div>
    <input v-model="message" />
    <div>v-model 语法糖</div>
    <!-- 在DOM事件的回调函数中传入参数$event,可以获取到该事件的事件对象 -->
    <!-- 写法1 -->
    <input :value="value" @input="value = $event.target.value" />
    <!-- 写法2 -->
    <input :value="value" @input="getData" />
    <!-- 写法3 -->
    <input :value="value" @input="(val) => (value = val.target.value)" />

    <!-- 父子组件使用v-model -->
    <child-cmp v-model="valueToChild"></child-cmp>
  </div>
</template>

<script>
import childCmp from "./childCmp.vue";
export default {
  components: { childCmp },
  data() {
    return {
      message: "v-model语法糖",
      value: "test",
      valueToChild: "",
    };
  },
  methods: {
    getData(val) {
      // 这边的val也是$event
      this.value = val.target.value;
    },
  },
};
</script>

子组件childCmp.vue

<template>
  <div>
    <input :value="value" @input="$emit('input', $event.target.value)" />
  </div>
</template>

<script>
export default {
  props: {
    value: String,
  },

  data() {
    return {};
  },
};
</script>

子组件也可以自定义规则

改变子组件必须接收 prop: value,$emit:input 的规则,使用model:{}

<template>
  <div>
    <input :value="otherValue" @input="$emit('input', $event.target.value)" />
  </div>
</template>

<script>
export default {
  // 使用自定义model
  model: {
    prop: "otherValue",
    // input也可以改成其他事件,如change
    event: "input",
  },
  props: {
    otherValue: String,
  },

  data() {
    return {};
  },
};
</script>

子组件在使用model时,prop和event不一定都在一个元素上

父组件

<template>
  <div>
    <button @click="valueToChild = false" >关闭显示</button>
    <child-cmp v-model="valueToChild"></child-cmp>
  </div>
</template>
<script>
import childCmp from "./childCmp.vue";
export default {
  components: { childCmp },
  data() {
    return {
      valueToChild: false,
    };
  },
};
</script>

子组件childCmp.vue

<template>
  <div>
    <div v-if="show">显示的内容.....</div>
    <!-- prop:"show" 和 event:"change" 不在同一个元素上 -->
    <button @click="$emit('change', true)">显示</button>
  </div>
</template>

<script>
export default {
  model: {
    prop: "show",
    event: "change",
  },
  props: {
    show: {
      type: Boolean,
      default: false,
    },
  },
};
</script>