Vue.js进阶技巧 Day03: 自定义组件v-model 实现

it2023-02-17  82

0x00 一种比较繁琐的方法

e-input.vue

<template> <input type="text" class='form-control' :value='val' @input="change"> </template> <script> export default{ props:['val'], methods:{ change(e){ console.log(e.target.value); this.$emit('change',e.target.value) } } } </script> <style> </style>

demo.vue

<template> <div> <h1 class='text-center'>{{val}}</h1> <e-input :val='val' @change='change'></e-input> </div> </template> <script> import eInput from './e-input.vue' export default{ components:{ eInput }, data(){ return { val:"请输入用户名" } }, methods:{ change(value){ this.val = value } } } </script> <style> </style>

0x01 使用model属性的简便写法

e-input.vue

<template> <input type="text" class='form-control' :value='val' @input="changeInput"> </template> <script> export default{ props:['val'], model:{ prop:'val', event:'change' }, methods:{ changeInput(e){ this.$emit('change',e.target.value) } } } </script> <style> </style>

demo.vue

<template> <div> <h1 class='text-center'>{{val}}</h1> <e-input v-model="val"></e-input> </div> </template> <script> import eInput from './e-input.vue' export default{ components:{ eInput }, data(){ return { val:"请输入用户名" } }, methods:{ change(value){ this.val = value } } } </script> <style> </style>

 

最新回复(0)