父子组件传值
父组件向子组件传值
若传入常量,直接在子组件标签上添加属性
字符串
<Child name= '朝阳' />
布尔值
必须加上:,否则会作为字符串传入
1. <C
简写方式:
<Child disabled />
默认传入的disabled值为true,若不写则相当于传入false
数值
必须加上:,否则会作为字符串传入
<Child :age= '30' />
变量
若传入变量,则必须使用:(v-bind指令的简写)
<Child :title="childTitle" />
子组件接收数据
子组件通过props接收父组件传入的数据
props: { title: String, },
子组件修改父组件传入的数据
1. 子组件通过 this.$emit 将新值传出
this.$emit("ChangeTitle", "新标题");
若需判断父组件是否绑定某事件
if(this.$emit('自定义事件名')){ …… }
2. 父组件引用子组件时,绑定$emit中对应的事件
<Child :tiltle="childTitle" @ChangeTitle="ChangeTitle" />
3. 父组件中绑定的事件接收子组件传出的新值
ChangeTitle(val) { this.childTitle = val; }
父子组件数据双向绑定
双向绑定会带来维护上的问题,因为子组件可以变更父组件,且在父组件和子组件都没有明显的变更来源。
所以,推荐以 update:myPropName 的模式触发事件来模拟双向绑定。(原文参见官网 https://cn.vuejs.org/v2/guide/components-custom-events.html#sync-修饰符)
update:实现父子组件数据双向绑定
父组件
<Child :childTitle="childTitle" @update:childTitle="childTitle = $event"/>
子组件
props: { childTitle: String, },
this.$emit("update:childTitle", "新标题")
.sync实现父子组件数据双向绑定
.sync
修饰符为update:模式提供了一种简写方式。
注意事项:带 .sync
修饰符的 v-bind
不能和表达式一起使用 (例如 v-bind:title.sync=”doc.title + ‘!’”
是无效的)
父组件中的
<Child :childTitle="childTitle" @update:childTitle="childTitle = $event"/>
可以直接简写为
<Child :childTitle.sync="childTitle"/>
子组件不变
props: { childTitle: String, },
this.$emit("update:childTitle", "新标题")
v-bind.sync实现父子组件数据双向绑定
若想实现多个数据的双向绑定,可以通过v-bind.sync绑定一个对象来实现(相比每个数据通过 .sync绑定,在书写上简化了很多)
注意事项:将 v-bind.sync 用在一个字面量的对象上,例如 v-bind.sync=”{ title: doc.title }”,是无法正常工作的,因为在解析一个像这样的复杂表达式的时候,有很多边缘情况需要考虑。
父组件
<Child v-bind.sync="childInfo" />
childInfo: { name: "张三", age: 30 }
子组件
props: { name: String, age: Number },
this.$emit("update:name", "新姓名"); this.$emit("update:age", 40);
v-model实现父子组件数据双向绑定
每个组件上只能有一个 v-model。
v-model
默认会占用名为 value
的 prop 和名为 input
的事件,以自定义二次封装的input 子组件为例:
父组件
<Child v-model="msg"/>
子组件
<input type="text" @input="changeMsg" />
props: { value: String, },
changeMsg(e) { this.$emit("input", e.target.value); },
通过model 可以自定义 v-model对应的prop名和事件名
父组件
<Child v-model="msg"/>
子组件
<input type="text" @input="changeMsg" />
model: { prop: "parentMsg", event: "changeMsg" }, props: { parentMsg: String, },
changeMsg(e) { this.$emit("changeMsg", e.target.value); },