Vue组件通信方法大全

父子组件通信

在这里插入图片描述

props down(父传子)

prpos传递数据

组件实例的作用域是孤立的,父组件不能直接使用子组件的数据,子组件也不能直接使用父组件的数据
父组件在模板中使用子组件的时候可以给子组件传递数据

     <bbb money="2"></bbb>

子组件需要通过props属性来接收后才能使用

    'bbb':{
        props:['money']
    }

如果父组件传递属性给子组件的时候键名有'-',子组件接收的时候写成小驼峰的模式

      <bbb clothes-logo='amani' clothes-price="16.58"></bbb>
      <script>
      props:['clothesLogo','clothesPrice']   子组件模板中:{{clothesLogo}}
	</script>

我们可以用 v-bind 来动态地将 prop 绑定到父组件的数据。每当父组件的数据变化时,该变化也会传导给子组件
1)父组件给子组件传递数据的时候
子组件需要利用props属性来确定自己的预期数据
2)如果 子组件 没有通过props属性接收传递过来的数据
则数据会议自定义属性的方式,放在 子组件 最外层的根元素上

  • 简单案例
   <div id="app">
        <father></father>
    </div>

    <template id="father">
        <div>
            <input type="text" v-model="pMsg">
            <p>这是father组件里的数据Pmsg => {{pMsg}}</p>
            <!-- 参数名字任意 要与props里保持一致  引号里的是父组件的数据 -->
               <!-- p-msg  驼峰法则 -->
            <son :p-msg="pMsg"></son>  
        </div>
    </template>

    <template id="son">
        <div>
            <p>这是son子组件,接收父组件传递的数据pMsg=>{{pMsg}}</p>
        </div>
    </template>
    
	<script>
	Vue.component("father",{
    template:"#father",
    data:function(){
        return{
            pMsg:"hello father"
        }
    },
    components:{
        son:{
            template:"#son",
            props:["pMsg"]  //接收父组件传递过来的参数 参数名字可以任意
        }
    }
})

new Vue({
    el:"#app"
})

在这里插入图片描述

单向数据流

Vue单向数据流的体现:数据只能从父级组件流向子级组件

Prop 是单向绑定的:当父组件的属性变化时,将传递给子组件,但是反过来不会。这是为了防止子组件无意间修改了父组件的状态,来避免应用的数据流变得难以理解。

另外,每次父组件更新时,子组件的所有 prop 都会更新为最新值。这意味着你不应该在子组件内部改变 prop。如果你这么做了,Vue 会在控制台给出警告。

注意在 JavaScript 中对象和数组是引用类型,指向同一个内存空间,如果 prop 是一个对象或数组,在子组件内部改变它会影响父组件的状态。因为这时更改的只是地址里的内容,并没有更改引用类型的内存地址,相当与没有更改这个引用类型数据

  • 单向数据流,子组件不能将数据传递给父组件,会报错
	<div id="app">
        <father></father>
    </div>

    <template id="father">
        <div>
            <input type="text" v-model="pMsg">
            <p>这是father组件里的数据Pmsg => {{pMsg}}</p>
            <!-- 参数名字任意 要与props里保持一致  引号里的是父组件的数据 -->
               <!-- p-msg  驼峰法则 -->
            <son :p-msg="pMsg"></son>  
        </div>
    </template>

    <template id="son">
        <div>
            <input type="text" v-model="pMsg">
            <p>这是son子组件,接收父组件传递的数据pMsg=>{{pMsg}}</p>
        </div>
    </template>
    
	<script>
	Vue.component("father",{
	    template:"#father",
	    data:function(){
	        return{
	            pMsg:"hello father"
	        }
	    },
	    components:{
	        son:{
	            template:"#son",
	            props:["pMsg"]  //接收父组件传递过来的参数 参数名字可以任意
	        }
	    }
	})
	
	new Vue({
	    el:"#app"
	})
	</script>
  • 子组件数据改变时,只会更改子组件自己的内容
    在这里插入图片描述
    在这里插入图片描述
  • 如果是引用类型,例如数组或者对象,可以进行引用类型里的数据更改
<div id="app">
        <father></father>
    </div>

    <template id="father">
        <div>
            <input type="text" v-model="pMsg.msg">
            <p>这是father组件里的数据Pmsg => {{pMsg.msg}}</p>
            <!-- 参数名字任意 要与props里保持一致  引号里的是父组件的数据 -->
            <!-- p-msg  驼峰法则 -->
            <son :p-msg="pMsg"></son>
        </div>
    </template>

    <template id="son">
        <div>
            <input type="text" v-model="pMsg.msg">
            <p>这是son子组件,接收父组件传递的数据pMsg=>{{pMsg.msg}}</p>
        </div>
    </template>

    <script src="./base/vue.js"></script>
    <script>

        Vue.component("father", {
            template: "#father",
            data: function () {
                return {
                    pMsg: {msg:"hello"}
                }
            },
            components: {
                son: {
                    template: "#son",
                    props: ["pMsg"]  //接收父组件传递过来的参数 参数名字可以任意
                }
            }
        })

        new Vue({
            el: "#app"
        })

    </script>

在这里插入图片描述

prpos验证

我们可以为组件的 prop 指定验证规则。
如果传入的数据不符合要求,Vue 会发出警告。这对于开发给他人使用的组件非常有用
props:{ num:填写验证规则, }

  • 验证主要分为:
    • 类型验证
      1.基础的类型检查 (nullundefined 会通过任何类型验证)
      num:Number
      2.多个可能的类型
      num:[Number,String]
    • 必传验证
      1.必填的字符串
      num:{ type:Number, required:true }
    • 默认值设置
    1. 带有默认值的数字
      num: { type: Number, default: 1000, }
      2…带有默认值的对象, 对象或数组默认值必须从一个工厂函数获取
      num: { type: Object, default: function () { return { message: 'hello' } } }
    • 自定义验证
      1.自定义验证函数, 这个值必须匹配下列字符串中的一个
      num: { validator(value){ return ['success', 'warning', 'danger'].indexOf(value) !== -1 }

props的值可以是对象,在里面可以对父组件传过来的数据做出验证,如果验证失败,会抛出警告

如果子组件没有通过props来接收父组件传递的某个数据,该属性就会出现在子组件模板的最外层节点上面

    <div id="app">
        <father></father>
    </div>

    <template id="father">
        <div>
            <p>我是father组件...</p>
            <hr>    
            <son :num="num"></son>
        </div>
    </template>

    <template id="son">
        <div>
            <p>我是son组件...{{num}}</p>
        </div>
    </template>

    <script src="./base/vue.js"></script>
    <script>

       new Vue({
    el: "#app",
    components: {
        father: {
            template: "#father",
            data() {
                return {
                    num:"hello"
                }
            },
            components: {
                son: {
                    template: "#son",
                    // props:[num],
                    props: {
                         // 1.基础的类型检查 (`null` 和 `undefined` 会通过任何类型验证)
                        // num:Number,
                        //2. 多个可能的类型
                        // num:[Number,String],
                        //3. 带有默认值的数字
                        // num: {
                        //     type: Number,
                        //     default: 1000,
                        // },
                        // 4.必填的字符串
                        // num:{
                        //     type:Number,
                        //     required:true
                        // },
                        // 5.带有默认值的对象
                        // num: {
                        //     type: Object,
                        // //对象或数组默认值必须从一个工厂函数获取
                        //     default: function () {
                        //         return { message: 'hello' }
                        //     }
                        // },
                        //6. 自定义验证函数
                        // num: {
                        //     validator(value){
                        //         // 这个值必须匹配下列字符串中的一个
                        //         return ['success', 'warning', 'danger'].indexOf(value) !== -1
                        //     }
                        // }
                    }
                }
            }
        }
    }
})
</script>

events up(子传父)

每一个组件或者实例都会有自定义事件,和触发事件的能力
父组件给子组件绑定一个自定义事件,这个事件的处理程序却是父组件的一个方法
<son @change="父组件的函数"></son>
当子组件触发这个事件的时候,相当于父组件的方法被执行了 this.$emit(自定义事件,参数)

<div id="app">
        <father></father>
    </div>

    <template id="father">
        <div>
            <p>这是父组件</p>
            <p>子组件传递的数据==>{{pMsg}}</p>
            <hr>
            <!-- 在调用子组件的时候,父组件需要给其自身绑定一个自定义事件 change -->
            <son @change="changeMsg"></son>
        </div>
    </template>

    <template id="son">
        <div>
            <p>这是子组件的数据==>{{msg}}</p>
            <p><button @click="say">将数据传递给父组件</button></p>
        </div>
    </template>
    
    <script src="./base/vue.js"></script>
    <script>

        Vue.component("father", {
            template: "#father",
            data() {
                return {
                    pMsg: ""  //1.需要在父组件内部声明一条数据
                }
            },
            methods: {
                changeMsg(msg) {  //2.父组件写一个更改自身数据的方法
                    this.pMsg = msg
                }
            }
        })

        Vue.component("son", {
            template: "#son",
            props: ["change"],
            data() {
                return {  //子组件的数据
                    msg: "hello"
                }
            },
            methods: {
                say() {
                    //需要触发父组件其自身绑定的change方法,   <son @change="changeMsg"></son>  并传入参数=>要传递的数据
                    this.$emit("change", this.msg)
                }
            }
        })
        new Vue({
            el: "#app"
        })
        </script>

在这里插入图片描述

v-model可以用在组件通信中

在组件上面使用v-model指令,相当于绑定了value属性与监听input事件。

 <div id="app">
        <child :value="myText" @input="handleEvent"></child>
        <childmodel v-model="myText"></childmodel>
    </div>

    <script src="./base/vue.js"></script>
    <script>

Vue.component("childmodel",{
        template:`<div>
                childmodel-{{value}}
                <button @click="handleClick">click</button>
            </div>`,
        props:["value"],
        methods:{
            handleClick(){
                this.$emit("input",222222222222)
            }
        }
    })


    Vue.component("child",{
        template:`<div v-once>
                child - {{value}}
                <button @click="handleClick">click</button>
            </div>`,
        props:["value"],
        methods:{
            handleClick(){
                //触发自身上面绑定的input的方法
                this.$emit("input",222222222222)
            }
        }
    })
    new Vue({
        el:"#app",
        data:{
            myText:"app"
        },
        methods:{
            handleEvent(text){
                this.myText = text
            }
        }
    })
    </script>

在这里插入图片描述

viewmodel链

组件、实例对象上有这样的属性:$parent,$children,$root,
$parent父组件$children[子组件索引]子组件
这样的话,就形成了viewmodel链(关系链)
理论上来说,任何两个组件之间的数据都 可以互相调用,获取
缺点:使用杂乱,复杂
例如 this.$root.$children[3].$children[4]....

  • 兄弟组件之间的通信
	<div id="app">
        <big-brother></big-brother>
        <hr>
        <little-brother></little-brother>
    </div>


    <template id="big-brother">
        <div>
            <p>我是哥哥</p>
            <button @click="hitLittle">打弟弟</button>
        </div>
    </template>

    <template id="little-brother">
        <div>
            <p>我是弟弟</p>
            <p v-if="crying">呜呜呜呜呜呜呜~~~~~~~~~~</p>
        </div>
    </template>

    <script src="./base/vue.js"></script>
    <script>

        Vue.component("big-brother", {
            template: "#big-brother",
            methods: {
                hitLittle() {
                    this.$parent.$children[1].crying=true  //关系链
                }
            }
        })

        Vue.component("little-brother", {
            template: "#little-brother",
            data() {
                return {
                    crying: false
                }
            }
        })
        new Vue({
            el: "#app"
        })
    </script>

在这里插入图片描述

ref链(兄弟之间通信)

在兄弟组件之间的通信,可以采用关系链和ref链去使用,解决兄弟之间通信问题。
给子组件添加ref属性<little-brother ref="little"></little-brother>
然后改变数据this.$parent.$refs.little.crying=true

    <div id="app">
        <big-brother></big-brother>
        <hr>
        <!-- 关系链 -->
        <little-brother ref="little"></little-brother>
    </div>


    <template id="big-brother">
        <div>
            <p>我是哥哥</p>
            <button @click="hitLittle">打弟弟</button>
        </div>
    </template>

    <template id="little-brother">
        <div>
            <p>我是弟弟</p>
            <p v-if="crying">呜呜呜呜呜呜呜~~~~~~~~~~</p>
        </div>
    </template>

    <script src="./base/vue.js"></script>
    <script>

        Vue.component("big-brother", {
            template: "#big-brother",
            methods: {
                hitLittle() {
                    this.$parent.$refs.little.crying=true     //通过关系链+ref链
                }
            }
        })

        Vue.component("little-brother", {
            template: "#little-brother",
            data() {
                return {
                    crying: false
                }
            }
        })
        new Vue({
            el: "#app"
        })
    </script>

在这里插入图片描述

事件总线bus

var bus = new Vue()
mounted生命周期中进行监听
在这里插入图片描述

 <div id="app">
        <big-brother></big-brother>
        <hr>
        <littel-brother></littel-brother>
    </div>


    <template id="big-brother">
        <div>
            <p>我是哥哥</p>
            <button @click="hitLittel">打弟弟</button>
        </div>
    </template>


    <template id="littel-brother">
        <div>
            <p>我是弟弟</p>
            <p v-if="crying">呜呜呜呜呜~</p>
        </div>
    </template>

    <script src="./base/vue.js"></script>
    <script>

        // 1.创建一个公共的vue的实例
        var angel = new Vue()

        
        Vue.component('big-brother', {
            template: '#big-brother',
            methods: {
                hitLittel() {
                    //3.触发事件hit
                    angel.$emit("hit")
                }
            }
        })
        Vue.component('littel-brother', {
            template: '#littel-brother',
            data() {
                return {
                    crying: false
                }
            },
            methods: {
                changeCrying() {
                    this.crying = true
                }
            },
            mounted() { //生命周期钩子函数     页面加载完成就会执行
                //2.绑定好事件       angle.$on(事件名,callback)
                angel.$on("hit", this.changeCrying)
            }
        })
        new Vue({
            el: "#app"
        })
    </script>

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值