为什么Vue组件的data是一个function?

请陛下批阅

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>为什么组件中的data是一个function</title>
    <script src="../../vue/vue-v2.6.11.js"></script>
</head>
<body>
<div id="app">
    <h1 style="color: red">
        <p>为什么data要定义为一个function?</p>
        <p>答: 解决数据共享问题,使得每个组件操作的数据互不干扰!!!</p>
    </h1>
    <mycom></mycom>
    <hr/>

    <mycom></mycom>
    <hr/>

    <mycom></mycom>
    <hr/>


</div>

<template id="tmpl">
    <div>
        <button @click="increment">+1</button>
        <h3>{{count}}</h3>
    </div>
</template>
</body>
<script>
    // 客官不可以(最好别这么定义组件中的 data,容易数据共享)
    // var dataObj = {count : 0};
    Vue.component('mycom', {
        template: '#tmpl',
        data: function () {
            return {count: 0};
        },
        methods: {
            increment() {
                this.count++;
            }
        }
    });
    var vm = new Vue({
        el: '#app',
        data: {}
    });
</script>
</html>
发布了62 篇原创文章 · 获赞 0 · 访问量 1247

猜你喜欢

转载自blog.csdn.net/weixin_45616246/article/details/105497260
今日推荐