父子祖孙组件通信

it2023-07-14  72

可以使用vue serve和vue build命令对单个*.vue文件进行快速原型开发,但需要安装一个全局的扩展: npm install -g @vue/cli-service-global支持.vue后缀文件(快速原型开发) 开发环境下:vue serve App.vue 生产环境下:vue build App.vue组件的通信 入口文件: <template> <div> <Parent></Parent> </div> </template> <style scoped> </style> <script> import Parent from './components/Parent'; export default{ data(){ return { } }, components:{ Parent } } </script>

components文件夹中建了三个vue 文件:Parent.vue Son.vue、grandSon.vue (1)父子通信 props $emit Parent.vue:

<template> <div> parent <!-- 父组件监听子组件的事件,并给事件绑定函数 --> <Son :m="money" @change="fn"></Son> </div> </template> <script> import Son from './Son'; export default{ data(){ return { // money:"ABC" money:500 } }, components:{ Son }, methods:{ fn(data){ this.money=data; } } } </script>

Son.vue:

<template> <div> son {{m}} {{a}} {{o}} <button @click="give">给父组件</button> <!-- {{changeM}} --> </div> </template> <script> export default{ props:{ m:{ type:[String,Number], required:true, validator:(value)=>{ //自定义验证规则 return value>400&value<2000 } }, //数组或者对象默认值是函数 a:{ type:Array, default:()=>[1] }, o:{ type:Object, default:()=>({}) } }, methods:{ give(){ //子组件执行父组件监听的事件 this.$emit('change',1000); } } // props:['m'], // computed:{ // changeM(){ // return this.m.trim().toLowerCase() // } // } } </script>

(2)语法糖的写法: Parent.vue Son.vue (3)v-model Parent.vue Son.vue

父组件批量传给子组件:$attrs——>如果继续向下传的话使用v-bind,子组件不需要使用props. 而子组件直接接收即可。 运行的结果以对象的形式展现:

传给grandson: Son.vue: 引入: 注册组件:

GrandSon.vue: 运行的结果如下:

传递事件,使用$listeners,继续向下传时使用v-on Son.vue 传给grandson时, Son.vue如下: grandson中: provide & inject Parent.vue: grandson中 $parent & $children 拿到父子组件的方法:

(2)或者使用ref

eventBus 兄弟之间传递数据 $on $emit Vue.prototype.$bus=new Vue; this.$bus.$on('test',function(data){console.log(data)}); this.$bus.$emit('test',1000)
最新回复(0)