父组件通过 props 传值给子组件,子组件通过 $emit 来通知父组件修改相应的props值,子组件可以通过watch监听父组件值变化。案例如下:
1.子组件
<template> <div class="com"> <input type="text" @input="inputChange" v-model="inputVal"> </div> </template> <script> export default { name: "myInput", props:['value'], data(){ return{ inputVal:this.value, } }, methods:{ inputChange(){ // 子组件值改变,通过$emit触发父组件方法,改变父组件值 this.$emit('input',this.inputVal) } }, watch:{ // 监听父组件值改变 value:function(newVal,oldVal){ this.inputVal = newVal; } } } </script> <style scoped> </style>
2. 父组件
<template> <div class="com"> <button @click="changeName"> change name</button> <v-input :value="name" @input="setName"></v-input> </div> </template> <script> import vInput from "@/components/issue/VInput" export default { name:"issueCom", components:{ vInput, }, data(){ return { name:"please", } }, methods:{ setName(val){ this.name = val; }, changeName(){ this.name += "**"; } } } </script> <style scoped> </style>