vue自定义组件中v-model的使用

1.v-model的实现是vue监听@input实现的

子组件代码如先

<!--
 
-->
<template>
  <div class="hello">
    <input v-model="newMsg" />
    <!-- <select @change="change" >
      <option value="12323">111</option>
       <option value="12">222</option>
    </select> -->
  </div>
</template>

<script>
export default {
  name: "helloWorld",
  model: {
    prop: 'msg',
    event:"input"
  },
  props: {
    msg: String,
  },

  data() {
    return {
      newMsg: ''
    }
  },
  watch: {
    newMsg(val) {
      this.$emit("input", val)
    },
    msg(val) {
      this.newMsg = val
    }
  },
  created() {
    this.newMsg = this.msg
  },
  methods: {
    change(val) {
      console.log(val.target.value);
      this.$emit("input", val.target.value)
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
父组件代码如下
<!--
 * @Author: your name
 * @Date: 2022-04-10 09:03:12
 * @LastEditTime: 2022-04-10 10:16:08
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \plugin\test\src\App.vue
-->
<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <!-- <helloWorld :msg="msg" @input="(val) => msg = val" /> -->
      <helloWorld v-model="msg" />
      {{msg}}
      <input v-model="msg"/>
  </div>
</template>

<script>
// import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  components: {
    // HelloWorld
  },
  data() {
    return {
      msg: 'wer'
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
posted @ 2022-04-10 10:46  关关大大  阅读(803)  评论(0编辑  收藏  举报