vue是单项数据流
父传子 --- props
props 能够写作数组或对象模式
Vue.component('ComponentA',{ // props:['msg'], // props能够写数组也能够写对象 props:{ msg:{ type:String,// 申明参数类型 default:'title---',// 默认值 required:true,// 必传参 }, name:{ type: Object, validator(val){ // 测验对象的值 console.log(val,'------') return val.a==1 } } }, template:'<div>{{msg}}</div>'})var vm = new Vue({ el:"#app", data:{ msg:'sxq' }, template:'<div>{{msg}}<ComponentA :msg="msg" :name="{a:1}"></ComponentA></div>'})
子传父 --- $emit
通过 $emit(自定义事件,参数)
办法传参给父组件
Vue.component('ComponentA',{ template:'<div @click="handleClick">click -- {{count}}</div>', data(){ return { count: 0 } }, methods: { handleClick(){ this.count++ this.$emit('test',this.count) } },})var vm = new Vue({ el:"#app", data:{ msg:'sxq' }, template:'<div>{{msg}}<ComponentA @test="handleTest"></ComponentA></div>', methods: { handleTest(count){ console.log(count) this.msg = count; } },})
v-model传值
将 $emit(自定义事件,参数)
中的自定义事件变为 input
事件,即可利用 v-model语法糖
的办法传递参数。
Vue.component('ComponentA',{ // model:{ // 能够更改默认值 // prop:'value_test', // 把默认的接管值 value 改为自定义的值 // event:'input_test' // 把默认事件 input 改为自定义的事件 // }, props:{ value:'' // 默认 事件为 input 接管值为 value }, template:'<div @click="handleClick">value -- {{value}}, count -- {{count}}</div>', data(){ return { count: 0 } }, methods: { handleClick(){ this.count = this.$props.value this.count++ this.$emit('input',this.count) } },})var vm = new Vue({ el:"#app", data:{ msg:0 }, template:'<div>{{msg}}<button @click="msg++">FADD</button><ComponentA v-model="msg"></ComponentA></div>'})
sync批改父组件的值
因为vue是单项数据流,子组件不能间接扭转父组件传递的参数,所以须要通过 sync 的办法扭转父组件的参数
$emit('update:自定义命名',改后的参数)
:自定义命名.sync="要改的参数"
Vue.component('ComponentA',{ props:['msg'], template:'<div>{{msg}}<button @click="handleClick">click</button></div>', data(){ return { count:0 } }, methods: { handleClick(){ this.count++; this.$emit('update:msg',this.msg + this.count) } },})var vm = new Vue({ el:"#app", data:{ msg:'sxq' }, template:'<div>{{msg}}<ComponentA :msg.sync="msg" :name="{a:1}"></ComponentA></div>'})