人生与戏

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

1. 全局组件创建

效果图: 1、创建新组件,  2. 实例化对象,  3.调用组件

 

 代码:

<!DOCTYPE html>
<html lang="en" >
<head>
    <meta charset="UTF-8">
    <title></title>
    <link type="text/css" rel="stylesheet" href=" "/>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="one">
    <!-- 3. 最后调用组件 -->
    <button-counter></button-counter>
    <button-counter></button-counter>
</div>
<script type="text/javascript">
    // 1.先在vue中定义一个名为 button-counter 的新组件
    Vue.component('button-counter',{
        // 定义数据函数  =》 每个实例返回独立的数据
        data:function(){
            return {
                count: 0
            }
        },
        // 定义组件模板内容
        template:'<button v-on:click="++count">You clicked me {{ count }} times</button>'
    });
    // 2.再将含有添加新组件的vue实例化给变量 vm
    var vm=new Vue({
        el:'#one',
        data:{ }
    });
</script>
</body>
</html>

 2. 局部组件创建

 

 代码:

<!DOCTYPE html>
<html lang="en" >
<head>
    <meta charset="UTF-8">
    <title></title>
    <link type="text/css" rel="stylesheet" href=" "/>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<!-- 局部注册组件 -->
<div id="two">
    <button_local></button_local>
</div>
<script type="text/javascript">
    var vm_local = new Vue({
        el:'#two',
        data:{
            info1: 'ha'
        },
        components:{
            button_local:{
                template: '<h1 @click="add">哈哈</h1>',
                methods:{
                    add:function(){
                        alert('你好!')
                    }
                }
            }
        }
    })
</script>
</body>
</html>

 

posted on 2019-09-23 23:09  人生与戏  阅读(162)  评论(0编辑  收藏  举报