Vue自定义组件:全局组件、局部组件0923

注意:
1、Vue自定义组件名,最好全部小写,词之间可用"-"隔开,比如:book-lists
2、template:"#tt_myFun1"和el:"#box1",都有:"#",不要漏写了。


<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>自定义组件:全局组件、局部组件</title>
    <style>

    </style>
</head>
<body>
    <h3>自定义组件大全</h3>
    <my-component1></my-component1>
    <!--1原始组件 -->
    <div id="box1">
        <h3>----------1.原始组件.begin------------</h3>
        <test></test>

        <div>
            <h3>------2.自定义组件begin-------------------</h3>
            <my-Component1></my-Component1>
            <h3>------自定义组件.end--------------</h3>
        </div>
    </div>

    <!--2.自定义组件-->
    <template id="tt3">
        <div>
            <p>hello everyone!</p>
            <span>这是组件的第2行</span>
        </div>
    </template>

    <!--3.带方法的自定义组件-->
    <template id="tt_myFun1">
        <div>
            <p @click="clickMe()">姓名:{{name}} ----年龄:{{age}}-----<span>点击次数:{{times}}</span></p>
        </div>
    </template>
    <div id="div_myFun1">
        <h3>------3.带方法的自定义组件begin-------------------</h3>
        <!--<test3></test3>-->
        <my-Funcomponent1></my-Funcomponent1>
        <span>一定要将驼峰命名,转化为:中间加一杠。myFuncomponent1-->my-Funcomponent1。Vue官方建议:全部小写。</span>
        <h3>------自定义组件.end--------------</h3>
    </div>


   <div id="div_myFun2">
       <h3>------4.给自定义组件传参begin-------------------</h3>
       <my-Com2 msg="书影音"
                imgsrc="http://pic.bizhi360.com/bpic/30/6730.jpg">
       </my-Com2>
       <h3>------自定义组件传参.end--------------</h3>
   </div>


 
    <template id="tt4">
        <div>
            <span>{{msg}}</span>
            <img v-bind:src="imgsrc">
        </div>
    </template>




</body>
<script src="https://cdn.bootcss.com/axios/0.16.2/axios.js"></script>
<script src="https://cdn.bootcss.com/vue/2.5.16/vue.min.js"></script>
<script >
  var times=5;
    // <!--1.全局组件-->
   Vue.component("test",{
       template:"<div>hello world!</div>"
       });

    Vue.component("myComponent1", {
        template: "#tt3"
    });

    var v1=new Vue({
          el:"#box1",
    }) ;

    // 带方法的自定义组件
    Vue.component("myFuncomponent1",{
       template:"#tt_myFun1",
       data:function () {
           return{
               name:"tom",
               age:18,
               times:5,
           }
       },
       methods:{
           clickMe:function () {
               this.times++;
               alert("点了"+ this.times+ "次了,烦不烦!");
           }
       }
    });

    var v2=new Vue({
        el:"#div_myFun1",
    //    带方法的自定义组件
    });




    //给自定义组件传参
     Vue.component("myCom2",{
          props:['msg','imgsrc'],
          template:"#tt4",
     });

    var v3= new Vue({
       el:"#div_myFun2",  //给自定义组件传参
    });






</script>
</html>

猜你喜欢

转载自blog.csdn.net/Golden_soft/article/details/82845701