vue_组件中的data和method

1、组件中的data

  组件可以有自己的data数据

  组件中的data和vue实例中的data不一样,实例中的data是一个对象,而组件中的data是一个方法!!,方法中还要有return一个对象,使用方式与vue实例一样,都是{{ msg }}插值表达式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>组件中的data</title>
</head>
<body>
    <div id="app">
       <mycom></mycom>
    </div>
</body>
    <!--1、导入vue包-->
    <script src="./js/vue.min.js"></script>
    <!--2、创建vue实例(new对象)-->
    <script type="text/javascript">
        Vue.component('mycom',{
            template:'<h1>这是全局组件-----{{msg}}</h1>',
            data:function(){
                return {
                    msg:'这是组件中的data数据'
                }
            }
        })
        var vm = new Vue({
           el:'#app',
           data:{
           },
           methods:{  
           }
        })
    </script>
</html>

 2、组件中的method

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>组件中的data</title>
</head>
<body>
    <div id="app">
       <mycom></mycom>
       <mycom></mycom>
       <mycom></mycom>
       
    </div>
    <template id="temp">
        <div>
            <input type="button" value="自增" @click="increment"/>
            <p>{{count}}</p>
        </div>
    </template>
</body>
    <!--1、导入vue包-->
    <script src="./js/vue.min.js"></script>
    <!--2、创建vue实例(new对象)-->
    <script type="text/javascript">
        Vue.component('mycom',{
            template:'#temp',
            data:function(){
                return {
                    count:0
                }
            },
            methods:{
                increment(){
                    this.count++
                }
            }
        })
        var vm = new Vue({
           el:'#app',
           data:{
           },
           methods:{  
           }
        })
    </script>
</html>

原文地址:https://www.cnblogs.com/hr-7/p/14807145.html