美文网首页
Vue不使用v-model的时候怎么监听数据变化?

Vue不使用v-model的时候怎么监听数据变化?

作者: 简单tao的简单 | 来源:发表于2023-12-15 08:50 被阅读0次

使用 v-model

parent

<template>
  <div id="app">
    <HelloWorld v-model="num" />

    <div style="margin-top:20px;">
      parentMsg is: {{ num }}
    </div>
  </div>
</template>

<script>
import HelloWorld from '../components/HelloWorld.vue'
export default {
  name: 'app',
  components: {
    HelloWorld
  },
  data() {
    return {
      num: 100
    }
  }
}
</script>

son

<template>
  <div class="hello">
    <h1>childMsg is: {{ num }}</h1>

    <button @click="fnClick">
      click to change childMsg
    </button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  model: {
    prop: 'num',
    event: 'aa'
  },
  props: {
    num: Number
  },
  data() {
    return {
    }
  },
  methods: {
    fnClick() { 
      this.$emit('aa',this.num+1)
    }
  }
}
</script>

不使用 v-model

parent

<template>
  <div id="app">
    <HelloWorld :num="num" @aa="fnAa" />

    <div style="margin-top:20px;">
      parentMsg is: {{ num }}
    </div>
  </div>
</template>

<script>
import HelloWorld from '../components/HelloWorld.vue'
export default {
  components: {
    HelloWorld
  },
  data() {
    return {
      num: 100
    }
  },
  methods: {
    fnAa(val) {
      this.num = val;
    }
  }
}
</script>

son

<template>
  <div class="hello">
    <h1>childMsg is: {{ num }}</h1>

    <button @click="fnClick">
      click to change childMsg
    </button>
  </div>
</template>

<script>
export default {
  props: {
    num: Number
  },
  data() {
    return {
    }
  },
  methods: {
    fnClick() { 
      this.$emit('aa',this.num+1)
    }
  }
}
</script>

相关文章

网友评论

      本文标题:Vue不使用v-model的时候怎么监听数据变化?

      本文链接:https://www.haomeiwen.com/subject/rnnwgdtx.html