vue 代码实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<div id="app">
    {{count}}
    <button @click="updateCount">clickMe</button>
    <hr>
    <hr>
    <h3 v-if="count<6" v-change="count">自定义指令</h3>

</div>
<script src="js/vue.min.js"></script>
<script>
    //1.model
    var exampleData ={
        msg:"hello vue",
        count:0
    };
    //2.viewmodel
    new Vue({
        el:"#app",
        data:exampleData,
        methods:{
            updateCount:function(){
               this.count++;
            }
        },
        directives:{   //所有自定义指令保存在此对象中
            change:{   //自定义指令change
                bind:function(el,bindings){
                    console.log(el);
                    console.log(bindings);
                    console.log("初始化指令");
                },
                update:function(el,bindings){
                    console.log("指令发生变化");
                    console.log(bindings.value);
                },
                unbind:function(el,bindings){
                    console.log("解除绑定");
                }
            }
        }
    });
</script>
</body>
</html>




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<div id="app">
    {{msg}}
    <br>
    <button @click="color">clickMe</button>
    <h3 v-if="count<6" v-change-background-color="myBgcolor">自定义指令</h3>

</div>
<script src="js/vue.min.js"></script>
<script>
    //1.model
    var exampleData ={
        msg:"hello vue",
        count:0,
       myBgcolor:"#ff0000"
    };
    //2.viewmodel
    new Vue({
        el:"#app",
        data:exampleData,
        methods:{
           color:function(){
               console.log(11);
               this.myBgcolor=this.getRandomColor();
           },
           getRandomColor:function(){
                var r=Math.floor(Math.random()*256);
                var g=Math.floor(Math.random()*256);
                var b=Math.floor(Math.random()*256);
                return `rgb(${r},${g},${b})`;
            }
        },
        directives:{   //所有自定义指令保存在此对象中
            changeBackgroundColor:{   //自定义指令change
                bind:function(el,bindings){  //el===h3
                    console.log("绑定成功");
                    el.style.backgroundColor = bindings.value;
                },
                //需要加更新的指令
                update:function(el,bindings){
                    el.style.backgroundColor = bindings.value;
                }
            }
        }
    });
</script>
</body>
</html>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<div id="app">
    <h4>{{price}}</h4>
    <h4>{{price | myCurrency('¥')}}</h4>
    <h4>{{price | myCurrency('$')}}</h4>

</div>
<script src="js/vue.min.js"></script>
<script>
    //1.model
    var exampleData ={
        msg:"hello vue",
        price:356
    };
    //2.viewmodel
    new Vue({
        el: "#app",
        data: exampleData,
        filters:{   //所有的过滤器定义在此处
            myCurrency:function(myInput,arg1){
                //参数myInput:price--过滤器前的变量值; arg1:¥
                var result=arg1+myInput;
                return result;


            }

        }
    });
</script>
</body>
</html>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<div id="app">
    <h4>{{text}}</h4>
    <h4>{{text | myTextTransform(true)}}</h4>
    <h4>{{text | myTextTransform(false)}}</h4>

</div>
<script src="js/vue.min.js"></script>
<script>
    //1.model
    var exampleData ={
        msg:"hello vue",
        text:"hello moto"
    };
    //2.viewmodel
    new Vue({
        el: "#app",
        data: exampleData,
        filters:{   //所有的过滤器定义在此处
            myTextTransform:function(myInput,arg1){
      //参数myInput:price--过滤器前的变量值==  |的值; arg1:¥
                if(arg1==true){
                    var result=myInput.toUpperCase();
                    return result;
                }else if (arg1==false){
                    var result=myInput.toLowerCase();
                    return result;
                }

            }

        }
    });
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<div id="app">
    <h3>自定义组件</h3>
    <hr>
  <!--完成组件的调用-->
    <my-component></my-component>
</div>
<script src="js/vue.min.js"></script>
<script>
    //创建组件
    Vue.component("my-component",{//模板
       template:`<div>
                     <h1>第一个组件</h1>
                     <h4>第一个</h4>
                  </div>`
    });
    //1.model
    var exampleData ={
        msg:"hello vue",

    };
    //2.viewmodel
    new Vue({
        el: "#app",
        data: exampleData,

    });
</script>
</body>
</html>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    <!--完成组件调用-->
    <button @click="isShow=!isShow">切换组件是否显示</button>
    <my-component v-if="isShow"></my-component>
</div>
<script src="js/vue.min.js"></script>
<script>
    //组件声明周期
    Vue.component('my-component',{
        template:`
            <div>
                <button @click="handleClick">clickMe</button>
                <h4>Hello {{count}}</h4>
            </div>
        `,
        data:function () {
            return {count:0}
        },
        methods:{
            handleClick:function () {
                //console.log('111');
                this.count ++;
               // console.log(this.count);
            }
        },
        beforeCreate:function(){console.log("1:创建前")},
        created:function(){console.log("2:创建后")},
        beforeMount:function(){console.log("3:挂在前")},
        mounted:function(){console.log("4:挂载后")},
        beforeUpdate:function(){console.log("5:更新前")},
        updated:function(){console.log("6:更新后")},
        beforeDestroy:function(){console.log("7:销毁前")},
        destroyed:function(){console.log("8:销毁后")},
    });

    var exampleData = {
        msg:'hello vue',
        isShow:true

    };
    new Vue({
        el:'#app',
        data:exampleData
    });
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<h3>自定义组件</h3>
<hr>
<div id="app">
    <!--完成组件的调用-->
    <my-component></my-component>
</div>
<script src="js/vue.min.js"></script>
<script>
    //创建组件 my_component
    //组件两个数据--myAddress  ;myPhone
    //添加模板
    //div_  添加两个input,input的value绑定刚才定义
    Vue.component("my-component",{
        data:function(){
            return{
                myAddress:"",
                myPhone:158
            }
        },
        template:`<div>
                      <input type="text" v-model="myAddress">
                      <input type="text" v-model="myPhone">
                      <h5>{{myAddress}}</h5>
                      <h5>{{myPhone}}</h5>
                  </div>
                   `,
        watch:{//监听事件
            myAddress:function(){
                console.log("数据发生改变:"+this.myAddress);
            },
            myPhone:function(){
                console.log("数据发生改变"+this.myPhone);
            }

        }
    });

    //1.model
    var exampleData ={
        msg:"hello vue",

    };
    //2.viewmodel
    new Vue({
        el: "#app",
        data: exampleData,

    });
</script>
</body>
</html>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    <!--完成组件调用-->
    <my-game></my-game>
</div>
<script src="js/vue.min.js"></script>
<script>
    //练习:透明度变化组件
    Vue.component("my-game",{
        data:function(){
            return {
                randomNumber:0,  //中奖数
                userInput:0,     //用户输入
                result:''
            }
        },
        mounted:function(){
            //console.log("3:挂在前");
            //创建中奖数1-100整数,并保存randomNumber
            var num=Math.floor(Math.random()*20);
            this.randomNumber=num;
        },
        template:`<div>
                      <input type="text" v-model="userInput"/>
                      <br>
                      <p>{{result}}</p>
                  </div> `,
        watch:{
            userInput:function(){
                //console.log(this.userInput);
                if(this.userInput>this.randomNumber){
                    this.result="大了";
                }else if(this.userInput<this.randomNumber){
                    this.result="小了";
                }else{
                    this.result="厉害了";
                }
            }
        }


    });

    var exampleData = {
        msg:'hello vue',
        isShow:true

    };
    new Vue({
        el:'#app',
        data:exampleData
    });
</script>
</body>
</html>

父子组件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<div id="app">
    <parent></parent>
</div>
<script src="js/vue.min.js"></script>
<script>
    //1.创建父组件
    Vue.component("parent",{
        data:function(){
            return {money:3000}
        },
        template:`
            <div>
                <h4>父组件</h4>
                <child :myValue="money"></child:mychild>
            </div>
        `
    });
    //2.创建子组件
    Vue.component("child",{
        template:`<div><h3>子组件{{myValue}}</h3></div>`,
        props:["myValue"],//声明变量 保存父组件的数据
        mounted:function(){
            //声明变量结束,获取父元素数据
            //已保存 this.data
            console.log(this.myValue);
        }
    });
    //3.创建Vue
    new Vue({
        el:"#app"
    });
</script>
</body>
</html>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div id="app">
        <parent></parent>
    </div>
    <script src="js/vue.min.js"></script>
    <script>
        Vue.component("parent",{
            data:function(){
                return {myCar:"QQ"}
            },
            template:`
                <div><child :car="myCar"></child></div>
            `

        });
        Vue.component("child",{
            props:["car"],
            template:`<div>{{car}}:
                            <input type="text" :value="car">
                      </div>`,
            mounted:function(){
                console.log(this.car);}
        });
        new Vue({
            el:"#app"
        });


    </script>
</body>
</html>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div id="app">
        <parent></parent>
    </div>
    <script src="js/vue.min.js"></script>
    <script>
        Vue.component("parent",{
            methods:{
                //1.1创建一个方法接收子组件传递的数据
                getData:function(msg){
                    console.log("父组件接收子组件的数据:"+msg);
                }
            },
            template:`
                <div>
                    <h4>父组件</h4>
                    <child @dataEvent="getData"></child>
                </div>
            `
        });
        Vue.component("child",{
            methods:{
                setData:function(){
                    //触发绑定自定义事件dataEvent并且传递的数据
                    this.$emit("dataEvent","交话费");
                }
            },
            template:`
                <div>
                    <h4>子组件</h4>
                    <button @click="setData">点击按钮发送数据给父组件</button>
                </div>
            `
        });
        new Vue({
            el:"#app"
        });
    </script>
</body>
</html>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div id="app">
        <parent></parent>
    </div>
    <script src="js/vue.min.js"></script>
    <script>
        //父
        Vue.component("parent",{
            data:function(){
                return {isUserLogin:true,list:[10,20,30,40,50]}
            },
            template:`<div>
                          <ul v-if="isUserLogin">
                            <li v-for="item in list" >{{item}}</li>
                          </ul>
                          <child @dataEvent="getData"></child>
                       </div>  `,
            methods:{
                getData:function(msg){
                    console.log("父组件接收子组件的数据:"+msg);
                    this.isUserLogin=msg;
                }
            }
        });
        //子
        Vue.component("child",{
            template:`
                <div><button @click="sendData">点击按钮发送数据给父组件</button></div>
            `,
            methods:{
                sendData:function(){
                    if(this.$parent.isUserLogin){
                        this.$emit("dataEvent",false);
                    }else{
                        this.$emit("dataEvent",true);
                    }
                }
            }
        });
        new Vue({
            el:"#app"
        });
    </script>
</body>
</html>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<div id="app">
    <parent></parent>
</div>
<script src="js/vue.min.js"></script>
<script>
    //父组件
    Vue.component("parent",{
        data:function(){
            return {name:"牛魔王"}
        },
        template:`<div>
                        <h4>父组件</h4><child ref="mySon"></child>
                        <button @click="getData">获取子组件</button>
                   </div>`,
        methods:{
            getData:function(){
                console.log("子组件名称:"+this.$refs.mySon.name);
            }
        }
    });
    //子组件
    Vue.component("child",{
        data:function(){
            return {name:"红孩儿"}
        },
        mounted:function(){
            console.log("父元素的数据:"+this.$parent.name);
        }
    });
    new Vue({
        el:"#app"
    });

</script>
</body>
</html>



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div id="app">
        <parent></parent>
    </div>
    <script src="js/vue.min.js"></script>
    <script>
        Vue.component("parent",{
            data:function(){
                return {name:["tom","jerry","kk"]}
            },
            template:`
                <div>
                    <ul >
                        <li v-for="item in name">{{item}}</li>
                    </ul>
                    <child></child>
                </div>
            `
        });
        Vue.component("child",{
            data:function(){
                return {userName:""}
            },
            template:`
                <div>
                    {{userName}}
                    <input type="text" value="" v-model="userName">
                     <button @click="setData">添加</button>
                </div>
            `,
            methods:{
                setData:function(){
                    //将用户名添加到父元素列表
                    var uname=this.userName;
                    this.$parent.name.push(uname);
                    //之后清空
                    this.userName="";

                }
            }
        });
        new Vue({
           el:"#app"
        });
    </script>

</body>
</html>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div id="app">
        <xiong-da></xiong-da>
        <xiong-er></xiong-er>
    </div>
    <script src="js/vue.min.js"></script>
    <script>
        //1.创建公共 Vue对象
        var bus=new Vue();
        //2.创建组件  xiong-er
        Vue.component("xiong-er",{
            template:`
                <div>
                    <h4>熊二接收数据</h4>
                    <h2>熊二发消息</h2>
                    <button @click="setData">熊二后发送</button>
                </div>
            `,
            methods:{
              setData:function(){
                  bus.$emit("eventEr","光头强走了!!!")
              }
            },
            mounted:function(){
                bus.$on("cutomeEvent",function(msg){
                    console.log("熊大发来的消息:"+msg);
                })
            }
        });
        //3.创建组件  xiong-da
        Vue.component("xiong-da",{
           template:`<div>
                          <h2>熊大接收数据</h2>
                         <h4>熊大发数据</h4>
                         <button @click="setData">发送</button>
                     </div>`,
           methods:{
               setData:function(){
                   bus.$emit("cutomeEvent","光头强又来啦");
               }
           },
           mounted:function(){
               bus.$on("eventEr",function(msg){
                 console.log("熊二发来的消息:"+msg);
               })
           }

        });
        //4.创建Vue
        new Vue({
           el:"#app"
        });
    </script>
</body>
</html>



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div id="app">
            <my-main></my-main>
    </div>
    <script src="js/vue.min.js"></script>
    <script>
        Vue.component("my-main",{
            data:function(){
                return {count:0, isValid:false}
            },
            template:`<div>
                          <h4>父组件</h4>
                          <button @click="addCount" :disabled="isValid">count++</button>
                          <son :myCount="count"></son>
                          <hr>
                      </div>`,
            methods:{
                addCount:function(){
                        this.count++;
                }
            }
        });
        Vue.component("son",{
            template:`<div>
                          <h4>子组件</h4>
                          <p>接收数据:{{myCount}}</p>
                      </div>`,
            props:["myCount"],
            //绑定生命周期方法:更新-->如果数据发生变化自动执行
            updated:function(){
                //console.log("子组件变化");
                console.log(this.myCount);
                if(this.myCount>10){//数据超过10
                    this.$parent.isValid=true;//禁用父组件按钮
                }
            }

        });
        new Vue({el:"#app"});
    </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div id="app">
        <!--2.显示不同组件的信息-->
        <router-view></router-view>
    </div>
    <script src="js/vue.min.js"></script>
    <!--1.引入路由的插件-->
    <script src="js/vue-router.js"></script>
    <script>
        //3.组件多个组件
        var testLogin=Vue.component("login",{
            template:`
                <div>
                      <h1>这是登录页面</h1>
                </div>
            `
        });
        var testRegister=Vue.component("register",{
            template:`
                <div>
                      <h1>这是注册页面</h1>
                </div>
            `
        });
        //4.配置路由词典
        //语法:请求路径     对应组件
        //{path:"/login",component:testLogin}
        const myRoutes=[
            {path:"",component:testLogin},
            {path:"/login",component:testLogin},
            {path:"/reg",component:testRegister}
        ];
        //5.创建路由对象
        const myRouter=new VueRouter({
            routes:myRoutes
        });
        //6.创建Vue对象,并且指定路由对象
        new Vue({
            router:myRouter,
            el:"#app"
        });

    </script>
</body>
</html>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        div{width:200px;  height:400px}
        #d{background: deepskyblue}
        #c{ background: greenyellow}
        #o{background: mediumvioletred}
    </style>
</head>
<body>
<div id="app">
    <!--2.显示不同组件的信息-->
    <router-view></router-view>
</div>
<script src="js/vue.min.js"></script>
<script src="js/vue-router.js"></script>
<script>
    var testCollect=Vue.component("collect",{
        template:`
                    <div id="c">
                        <h4>收藏页面</h4>
                        <router-link to="/detail">详情页面</router-link>
                        <router-link to="/order">订单页面</router-link>
                    </div>
                `
    });
    var testDetail=Vue.component("detail",{
        template:`
                    <div id="d">
                        <h4>详情页面</h4>
                        <router-link to="/order">查看订单页面</router-link>
                        <router-link to="/collect">查看收藏页面</router-link>
                    </div>
                `
    });
    var testOrder=Vue.component("order",{
        template:`
                    <div id="o">
                        <h4>订单页面</h4>
                        <button @click="jumpToCollect">返回收藏</button>
                        <button @click="jumpToDetail">返回详情</button>
                    </div>
                `,
        methods:{
            jumpToCollect:function(){
                //通过js的方式,实现导航到指定的路由地址对应的组件
                this.$router.push("/collect");
            },
            jumpToDetail:function(){
                //通过js的方式,实现导航到指定的路由地址对应的组件
                this.$router.push("/detail");
            }
        }

    });
    const myRoutes=[
        {path:"",component:testCollect},
        {path:"/collect",component:testCollect},
        {path:"/detail",component:testDetail},
        {path:"/order",component:testOrder}
    ];
    //5.创建路由对象
    const myRouter=new VueRouter({
        //路由对象里,引用要使用的路由词典
        routes:myRoutes
    });
    //6.创建Vue对象,并且指定路由对象
    new Vue({
        router:myRouter,
        el:"#app"
    });

</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        div{width:300px;  height:400px}
        #l{background: cornflowerblue; color: aliceblue}
        #d{background: lightseagreen; color: greenyellow}
    </style>
</head>
<body>
<div id="app">
    <!--2.显示不同组件的信息-->
    <router-view></router-view>
</div>
<script src="js/vue.min.js"></script>
<!--1.引入路由的插件-->
<script src="js/vue-router.js"></script>
<script>
    //3.组件多个组件
    //接收参数
    var productDetail=Vue.component("product-detail",{
        data:function(){
          return {productId:0}//接收上一个组件传来的参数
        },
        template:`
            <div id="d">
                <h2>{{productId}}</h2>
                <router-link to="/list">返回list</router-link>
            </div>
        `,
        mounted:function(){
            this.productId= this.$route.params.pid;
            console.log(this.$route.params);
        }
    });

    //发送参数
    var productList=Vue.component("product-list",{
        data:function(){
            return {list:["aaa","bbb","ccc","ddd","eee"]}
        },
        template:`
            <div id="l">
                <h3>产品列表</h3>
                <ul>
                    <li v-for="(item,idx) in list">
                    <router-link :to="'/detail/'+idx">{{item}}</router-link>
                    </li><br>
                    <button @click="toDetail">进入详情页</button>
                </ul>
            </div>
        `,
        methods:{
            toDetail:function(){
                this.$router.push("/detail/"+this.list);
            }
        }
    });

    var NotFound =Vue.component("my-found",{
        template:`<div class="base">
                        <h1> 404 Page Not Fount</h1>
                        <router-link to="/login">返回首页</router-link>
                   </div>`
    });

    //4.配置路由词典
    const myRoutes=[
        {path:"",component:productList},
        {path:"/list",component:productList,alias:"/lists"},
        {path:"/mylist",redirect:"/list"},
        {path:"/detail/:pid",component:productDetail},
        {path:"*",component:NotFound}
    ];

    //5.创建路由对象
    const myRouter=new VueRouter({
        routes:myRoutes
    });
    //6.创建Vue对象,并且指定路由对象
   new Vue({
       router:myRouter,
       el:"#app"
   });


</script>
</body>
</html>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        div{width:300px;  height:400px}
        #l{background: cornflowerblue; color: aliceblue}
        #m{background: lightseagreen; color: greenyellow}
    </style>
</head>
<body>
<div id="app">
    <!--2.显示不同组件的信息-->
    <!--显示login和main-->
    <router-view></router-view>
</div>
<script src="js/vue.min.js"></script>
<!--1.引入路由的插件-->
<script src="js/vue-router.js"></script>
<script>
    //3.组件多个组件login/main/inbox/outbox
    var myLogin=Vue.component("my-login",{
        template:`
            <div id="l">
                <h4>登录组件</h4>
                <router-link to="/main">跳到主页面</router-link>
            </div>
        `
    });
    var myMain=Vue.component("my-main",{
        template:`
            <div id="m">
                <h3>邮箱主页面</h3>
                <ul>
                    <li><router-link to="/inbox">收件箱</router-link></li>
                    <li><router-link to="/outbox">发件箱</router-link></li>
                </ul>
                <router-view></router-view>
            </div>
        `
    });
    var myInbox=Vue.component("my-inbox",{
        template:`
            <div id="m">
                <ul>
                    <li>未读邮件1</li>
                    <li>未读邮件2</li>
                    <li>未读邮件3</li>
                    <li>未读邮件4</li>
                </ul>
            </div>
        `
    });
    var myOutbox=Vue.component("my-outbox",{
        template:`
            <div id="m">
                <ul>
                    <li>已发邮件1</li>
                    <li>已发邮件2</li>
                    <li>已发邮件3</li>
                    <li>已发邮件4</li>
                </ul>
            </div>
        `
    });

    //4.配置路由词典
    const myRoutes=[
        {path:"",redirect:"/login"},
        {path:"/login",component:myLogin},
        {path:"/main",component:myMain,
            children:[
                {path:"/inbox",component:myInbox},
                {path:"/outbox",component:myOutbox},
            ]
        },
    ];

    //5.创建路由对象
    const myRouter=new VueRouter({
        routes:myRoutes
    });
    //6.创建Vue对象,并且指定路由对象
    new Vue({
        router:myRouter,
        el:"#app"
    });


</script>
</body>
</html>
相关推荐
©️2020 CSDN 皮肤主题: 程序猿惹谁了 设计师:白松林 返回首页