1,子组件通过v-model属性获取父组件的数据
子组件:
<template>
<div>
{{value}}
</div>
</template>
<script>
export default {
props : {
value : [String, Number]
}
}
</script>
父组件:
<template>
<div>
<test v-model="active"></test>
</div>
</template>
<script>
import test from './test';
export default {
data () {
return {
active:2
}
}
2,子组件通过v-model获取父组件的数据,子组件改变父组件的数据
子组件:
<template>
<div>
<div>{{msg}}</div>
<div>
<ul>
<li v-for="(item,index) in option" :key="index" @click="Change(item)">{{item}}</li>
</ul>
</div>
</div>
</template>
<script>
export default {
props:['option','msg'],
model:{
prop:'msg',
event:'cc'
},
methods:{
Change(data){
this.$emit('cc',"我变了");
}
},
mounted(){
console.log(this.msg);
}
}
</script>
父组件使用:
<z-select v-model="val" :option="option"></z-select>
data () {
return {
option:["aaa","bbb","ccc"],
val:"请输入"
}
},
3,[endif]父组件通过v-model模仿 input标签的v-model属性
<template>
<div>
<input type="text" v-model="newValue" @input="change">
</div>
</template>
export default {
props: ['value'],
data(){
return {
newValue:this.value
}
},
methods:{
change(){
this.$emit("input", this.newValue);
}
},
}
备注;
父组件的v-model值接收子组件中props中的value值
子组件初始化newValue的值为父组件v-model中接收的值
之后子组件不断的改变并发射input事件,送出newValue值
子组件的另一种写法:
<template>
<div>
<input type="text" v-model="newValue" @input="change">
</div>
</template>
<script>
export default {
props: ['value'],
data(){
return {
newValue:this.value
}
},
methods:{
change(){
this.$emit("input", this.newValue);
}
},
computed:{
newValue:{
get(){
return this.value;
},
set(value){
this.$emit("input",value);
}
}
}
}
</script>
父组件:
<input-ele v-model="active" @input="getValue"></input-ele>
getValue(event){
console.log(event,"接收文本框输入的值");
}