How vue2 custom components use v-model

1. v-modelProblems to be solved

When using custom components, we sometimes need to use v-modelto 双向绑定.

Two, the default use

In vue, v-modelthe value is equivalent to 默认passing a name value 的 propand a name input 的方法(note that this valueneeds propto be declared in the custom component), as follows:

<template>
  <div>
    <p><a @click="click()">add</a></p>
    <p>CTnum: {
   
   { num }}</p>
  </div>
</template>

<script>
export default {
      
      
  name: "CT",
  props: {
      
      
    value: {
      
      
      type: Number,
      default: 0,
    },
  },
  data() {
      
      
    return {
      
      
      num: this.value,
    };
  },
  mounted() {
      
      },
  methods: {
      
      
    click() {
      
      
      this.num++;
      this.$emit("input", this.num);
    },
  },
};
</script>
<template>
  <div>
    <p>BT</p>
    <CT v-model="num"></CT>
    <p>BTnum: {
   
   { num }}</p>
  </div>
</template>

<script>
import CT from "./CT.vue";

export default {
      
      
  name: "BT",
  components: {
      
       CT },
  data() {
      
      
    return {
      
      
      num: 0,
    };
  },
  mounted() {
      
      },
  methods: {
      
      },
};
</script>

3. Custom use

When used by default, 事件名inputand prop名valueare fixed, if you need to modify, you need to use modeloptions in subcomponents. as follows:

<template>
  <div>
    <p><a @click="click()">add</a></p>
    <p>CTnum: {
   
   { num }}</p>
  </div>
</template>

<script>
export default {
      
      
  name: "CT",
  model: {
      
      
    prop: 'modelvalue',
    event: 'change'
  },
  props: {
      
      
    modelvalue: {
      
      
      type: Number,
      default: 0,
    },
  },
  data() {
      
      
    return {
      
      
      num: this.modelvalue,
    };
  },
  mounted() {
      
      },
  methods: {
      
      
    click() {
      
      
      this.num++;
      this.$emit("change", this.num);
    },
  },
};
</script>
<template>
  <div>
    <p>BT</p>
    <CT v-model="num"></CT>
    <p>BTnum: {
   
   { num }}</p>
  </div>
</template>

<script>
import CT from "./CT.vue";

export default {
      
      
  name: "BT",
  components: {
      
       CT },
  data() {
      
      
    return {
      
      
      num: 0,
    };
  },
  mounted() {
      
      },
  methods: {
      
      },
};
</script>

Guess you like

Origin blog.csdn.net/letianxf/article/details/128429039