封装组件v-model的简易实现

123 阅读1分钟
<div id="app">      <!-- 1\. 把 v-model 添加到 input DOM元素  ok  -->      <!-- <input type="text" v-model="name"> -->      <!-- 2\. 把 v-model 拆解  v-model => v-bind(M=>V)和v-on(V=>M) -->      <!-- <input type="text" :value="msg" @input="iptn"> -->      <!-- 3\.  把 事件里面的赋值代码 改造 为模板里面的代码   -->      <!-- <input type="text" :value="msg" @input="msg = $event.target.value" /> -->      <!-- 在DOM元素上加都是ok, 在自定义组件上 需要我们自己处理 -->      <mingge-input v-model="msg"></mingge-input>         <!-- $event 默认 是 mingge-input传递过来的值0 -->      <!-- <mingge-input :value="msg" @input="msg=$event"></mingge-input> -->   </div>            <script src="vue.js"></script>   <script>       // 组件       Vue.component('mingge-input', {          props: ['value'],          template: `          <div>             子组件 :  <input :value='value' @input='iptFn' />          </div>            `,          methods: {            iptFn(e) {              console.log(e.target.value)              this.$emit('input', e.target.value)            },          }       })                // 实例        const vm = new Vue({          el: '#app',          data: {            msg: '刘明',            name: 'xiaoming'          },          methods: {            // iptn (e) {            //   // e.target.value 就是input的值            //   this.msg = e.target.value            // }          }        })   </script>