一个代码仓库,理解 Vue 项目中组件之间的通信

3次阅读

共计 952 个字符,预计需要花费 3 分钟才能阅读完成。

父组件传给子组件:
1、props 方式:父组件通过 Prop 向子组件传递数据(推荐使用)项目中访问路由:http://localhost:8080/parent_to_child/props
2、slot 方式:父组件通过 v-slot 设置值,子组件通过带 name 的 slot 接收值(推荐使用)项目中访问路由:http://localhost:8080/parent_to_child/slot
3、refs 方式:父组件通过 ref 设置子组件的值(可以使用)项目中访问路由:http://localhost:8080/parent_to_child/refs
4、$children 方式:父组件通过 $children 设置子组件的值($children 并不保证顺序,开发者不应该依赖子组件的顺序,也不是响应式的)(节制使用)项目中访问路由:http://localhost:8080/parent_to_child/children
子组件传给父组件:
1、自定义事件方式:父组件通过 v-on 监听子组件的事件,然后父组件使用子组件触发事件抛出的值(本例中,值是一个 1 到 100 之内的随机数)项目中访问路由:http://localhost:8080/child_to_parent/v-on_emit
2、子组件直接修改父组件传来的 prop 子组件可以直接修改父组件传来的引用类型 prop;子组件直接修改接收的基本类型 prop,会报错(如果一定要这样做,以 update:myPropName 的模式触发事件实现,即.sync 修饰符方式)项目中访问路由:http://localhost:8080/child_to_parent/child_component_change_prop
3、.sync 修饰符 方式:子组件修改父组件传来的 prop,然后 emit 一个 update 事件,父组件监听该事件并更新自己的 prop(是自定义事件的语法糖)项目中访问路由:http://localhost:8080/child_to_parent/sync_emit_update
4、$parent 方式:子组件通过 $parent 设置父组件的值(节制使用)项目中访问路由:http://localhost:8080/child_to_parent/parent

正文完
 0