1. 程式人生 > 其它 >20vue學習_元件裡的資料,以data函式的形式

20vue學習_元件裡的資料,以data函式的形式

技術標籤:VUE

1、元件裡的資料以DATA函式的形式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title-hellovuejs</title>
</head>
<body>
    <div id ="app">
        <!-- 3.使用元件 -->
        <my_cpn1></my_cpn1>
        <my_cpn2></my_cpn2>
    </div>
    <!-- 1.模板分離寫法1 ,script標籤,型別必須是text/x-template-->
    <script type="text/x-template" id="cpn1">
        <div>
            <h2>我是標題</h2>
            {{cpmessage1}}
            <p>這是內容,模板分離寫法1,script標籤</p>
        </div>    
    </script>

    <!-- 2.模板分離寫法2 ,推薦,使用template標籤-->
    <template id="cpn2">
        <div>
            <h2>我是標題2</h2>
            {{cpmessage2}}
            <p>這是內容,模板分離寫法2,使用template標籤</p>
        </div>            
    </template>

    <script src="../js/vue.js"></script>
    <script>
        //1.通過語法糖建立全域性元件,模板分離寫法1
        //注意,使用了tab鍵上面的反斜槓``,因而可以換行定義
        Vue.component('my_cpn1',{
            template: '#cpn1',
            data(){
                return {
                    cpmessage1: '訊息data11'
                }
            }
        });
        //root元件
        const chen1 = new Vue({
            el: '#app',  //用於掛載要管理的元素
            data:{//定義資料
                message:'你好啊,helloword',
                isShow: true
            },
            //2 以下語法糖形式直接建立是區域性元件的用法
             components:{
                my_cpn2: {
                    template:'#cpn2',
                    data(){
                        return {
                            cpmessage2: '訊息data22'
                        }
                    }
                }
            }
        })
    </script>
</body>

2、計陣列件的例子

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title-hellovuejs</title>
</head>
<body>
    <div id ="app">
        <!-- 3.使用元件 -->
        <my_cpn1></my_cpn1>
        <my_cpn1></my_cpn1>
    </div>
    <!-- 模板分離寫法2 ,推薦,使用template標籤-->
    <template id="cpn1">
        <div>
            <h2>當前計數:{{counter}}</h2>
            <button @click="increment">+</button>
            <button @click="decrement">-</button>
        </div>            
    </template>

    <script src="../js/vue.js"></script>
    <script>
        //1.通過語法糖建立全域性元件,模板分離寫法1
        //注意,使用了tab鍵上面的反斜槓``,因而可以換行定義
        Vue.component('my_cpn1',{
            template: '#cpn1',
            data(){
                return {
                    counter: 0
                }
            },
            methods:{
                increment(){
                    this.counter++
                },
                decrement(){
                    this.counter-- 
                }
            }
        });
        //root元件
        const chen1 = new Vue({
            el: '#app',  //用於掛載要管理的元素
            data:{//定義資料
                message:'你好啊,helloword',
            }      
        })
    </script>
</body>