美文网首页
vue 脚手架搭建得项目之间得传值

vue 脚手架搭建得项目之间得传值

作者: 北街九条狗 | 来源:发表于2020-03-19 14:43 被阅读0次

父传子

父组件

    <div id="box">
        <aaa></aaa>//父组件
    </div>

    <template id="aaa">
      <div>
          <h1>11111</h1>
          <bbb :m="msg"></bbb>//子组件绑定父组件传的值
      </div>
    </template>
    <script>
        var vm=new Vue({
            el:'#box',
            data:{
                a:'aaa'
            },
            components:{
                'aaa':{
                    data(){
                        return {
                            msg:'我是父组件的数据'
                        }
                    },
                    template:'#aaa',
                    components:{
                        'bbb':{
                            props:['m'],//子组件通过props获取绑定父组件的值
                            template:'<h3>我是bbb组件->{{m}}</h3>'
                        }
                    }
                }
            }
        });
    </script>

子传父

    <div id="box">
        <aaa></aaa>
    </div>
    <template id="aaa">
      <div>
         <span>我是父级 -> {{msg}}</span>
        <bbb @child-msg="get"></bbb>//绑定get方法
      </div>
    </template>
    <template id="bbb">
      <div>
        <h3>子组件-</h3>
        <input type="button" value="send" @click="send">//子组件绑定传送方法
        </div>
    </template>
    <script>
        var vm=new Vue({
            el:'#box',
            data:{
                a:'aaa'
            },
            components:{
                'aaa':{
                    data(){
                        return {
                            msg:111,
                            msg2:'我是父组件的数据'
                        }
                    },
                    template:'#aaa',
                    methods:{
                        get(msg){
                            this.msg=msg;//将获取到的值赋给自己的属性中
                        }
                    },
                    components:{
                        'bbb':{
                            data(){
                                return {
                                    a:'我是子组件的数据'
                                }
                            },
                            template:'#bbb',
                            methods:{
                                send(){
                                    this.$emit('child-msg',this.a);//将值传出
                                }
                            }
                        }
                    }
                }
            }
        });
    </script>

*注

如果子组件是用路由引入的,可以将绑定方法写到路由中

<bbb @child-msg="get"></bbb>//绑定get方法
===>
<router-view @numNew="get" @aaa="getNoticeTheNumber" />

相关文章

网友评论

      本文标题:vue 脚手架搭建得项目之间得传值

      本文链接:https://www.haomeiwen.com/subject/dlgyactx.html