zoukankan      html  css  js  c++  java
  • Vue组件父子间通信01

    子组件传递数据 用户已经登录

    父组件接收数据 并显示列表,未登录不显示列表

    /*
    有两个组件,分别是main-component,header-component.
    main-component是由header-component和一个列表(有5条数据 [100,200,300,400,500]),
    header-component是由一个h1的标签:'这是页头',有一个数据isUserLogin:true

    在渲染main-component时候,读取header-component在挂载完毕之后通过事件传递来的数据(isUserLogin),根据该数据的真假来决定列表是否显示.

    <child-component @myEvent="recvMsg">
    </child-component>

    this.$emit('myEvent',myPhone)
    */

    <!doctype html>
    <html>
     <head>
      <meta charset="UTF-8">
      <title>子与父通信</title>
        <script src="js/vue.js"></script>
     </head>
     <body>
      <div id="container">
            <p>{{msg}}</p>
            <main-component></main-component>
        </div>
        <script>
        
    //创建父组件
            Vue.component("main-component",{
                data:function(){
                    return{
                        myList:[1,2,3,4,5],
                        isUserLogin:true
                    }
                },
                methods:{
                    recvMsg:function(msg){
                        this.isUserLogin = msg;
                    }
                },
                template:`
                <div>
                    <header-component @checkUserLogin="recvMsg"></header-component>
                    <ul v-if="isUserLogin">
                        <li v-for="tmp in myList">{{tmp}}</li>
                    </ul>
                </div>`
            })
            //创建子组件
            Vue.component("header-component",{
            //data属性中保存用户已经登录
                data:function(){
                    return{
                        isLogin:false
                    }
                },
                //通过$emit在挂载完成后把用户已经登录的值发传递给父组件
                mounted:function(){
                        this.$emit("checkUserLogin",this.isLogin);
                },
                template:`
                    <div>
                        <h1>这是页头</h1>
                    </div>
                `
            })
    //    new一个vue实例
            new Vue({
                el:"#container",
                data:{
                    msg:"Hello VueJs"
                }
            })
        </script>
     </body>
    </html>
  • 相关阅读:
    图标字体IcoMoon 使用
    JS 寻找孩子并打印路径
    为什么要用on()而不直接使用click
    setTimeout 虚假的“异步”
    解决Ajax.BeginForm还是刷新页面的问题
    .net生成Excel,并下载
    C#判断文件是否正在被使用
    sql为数字添加千分位(也就是钱的格式)
    HotelIInventory项目小结
    一步一步实现FormsAuthentic验证登录
  • 原文地址:https://www.cnblogs.com/wangruifang/p/7771812.html
Copyright © 2011-2022 走看看