Vue的學習筆記-Day4-01(父組件向子組件傳值、評論列表、ref的使用)

一、父組件向子組件傳值

<div id="app">
    <!--父組件可以在引用子組件的時候,通過屬性綁定{v-bind:}的形式,把需要傳遞給子組件的數(shù)據(jù),以屬性綁定的形式,傳遞到子組件內(nèi)部,供子組件使用-->
    <com1 :parentmsg="msg "></com1>
</div>

<script>
    var vm = new Vue({
        el: '#app',
        data: {
            msg: '父組件的數(shù)據(jù)'
        },
        methods: {},
        components: {
            //子組件中默認無法訪問到父組件中的data上的數(shù)據(jù)和methods中的方法
            com1: {
                data() {//子組件中的data數(shù)據(jù)并不是通過父組件傳遞過來的,而是子組件自身私有的
                    return {
                        title: '123',
                        content: 'qqq'
                    }
                },
                template: '<h1>這是子組件 --- {{parentmsg}}</h1>',
                /*組件中的所有props中的數(shù)據(jù),都是通過父組件傳遞給子組件的*/
                /*props中的數(shù)據(jù)只是可讀的,不可以改變,而data中的數(shù)據(jù)可讀可寫*/
                props: ['parentmsg']//把父組件傳遞過來的parentmsg屬性,現(xiàn)在props數(shù)組中定義一下,這樣才能使用這個數(shù)據(jù)
            }
        }
    })
</script>

二、父組件把方法傳遞給子組件同時傳值

<div id="app">
    <!--父組件向子組件傳遞方法,使用的是事件綁定機制 v-on: 當我們自定義了一個事件屬性之后,子組件可以通過某些方法來調(diào)用傳遞進去的這個方法-->
    <com2 @func="show"></com2>
</div>

<template id="tmpl">
    <div>
        <h1>這是子組件</h1>
        <input type="button" value="這是子組件中的按鈕 - 點擊它,觸發(fā)父組件傳遞出來的func方法" @click="myClick">
    </div>
</template>

<script>

    var com2 = {
        template: '#tmpl',
        data() {
            return {
                sonmsg: {name: '小頭兒子', age: 6}
            }
        },
        methods: {
            myClick() {
                //emit 英文原意是觸發(fā)的意思
                this.$emit('func', this.sonmsg, 456);
            }
        }
    };


    var vm = new Vue({
        el: '#app',
        data: {
            dataMsgFromSon: null
        },
        methods: {
            show(data, data2) {
                // console.log('調(diào)用了父組件身上的show方法---' + data + '---' + data2);
                // console.log(data);
                this.dataMsgFromSon = data;
            }
        },
        components: {
            com2
        }
    })
</script>

三、組件案例-評論列表

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="lib/bootstrap.css">
    <script src="lib/vue-2.6.10.js"></script>
</head>
<body>

<div id="app">

    <cmt-box @func="loadComments"></cmt-box>

    <ul class="list-group">
        <li class="list-group-item" v-for="(item,i) in list" :key="item.i">
            <span class="badge">評論人:{{item.user}}</span>
            {{item.content}}
        </li>
    </ul>

</div>

<template id="tmpl">
    <div>
        <div class="form-group">
            <label>評論人:</label>
            <input type="text" class="form-control" v-model="user">
        </div>

        <div class="form-group">
            <label>評論內(nèi)容:</label>
            <textarea class="form-control" v-model="content"></textarea>
        </div>

        <div class="form-group">
            <input type="button" value="發(fā)表評論" class="btn btn-primary" @click="postComment">
        </div>
    </div>
</template>

<script>
    var commentBox = {
        data() {
            return {
                user: '',
                content: ''
            }
        },
        template: '#tmpl',
        methods: {
            postComment() {//發(fā)表評論的方法
                //分析發(fā)表評論的業(yè)務邏輯
                //1、評論數(shù)據(jù)存到 localStorage
                //2、先組織一個最新的評論數(shù)據(jù)對象
                //3、想辦法把第二步得到的評論對象保存到localStorage
                //3.1、localStorage只支持存放字符串,要先調(diào)用JSON.stringify
                //3.2、在保存最新的評論數(shù)據(jù)之前,要先從localStorage獲取到之前的評論數(shù)據(jù),把最新的評論push到這個數(shù)組
                //3.3、如果獲取到的評論字符串為空或者不存在,則可以返回一個'[]',讓JSON.parse去轉(zhuǎn)換
                //3.4、把最新的評論列表數(shù)組,再次調(diào)用JSON.stringify轉(zhuǎn)換為數(shù)組字符串,然后調(diào)用localStorage.setItem();

                var comment = {id: Date.now(), user: this.user, content: this.content};

                /*從localStorage中獲取的所有評論*/
                var list = JSON.parse(localStorage.getItem('cmts') || '[]');
                list.unshift(comment);
                localStorage.setItem('cmts', JSON.stringify(list));
                this.user = this.content = '';

                this.$emit('func');
            }
        }
    };

    var vm = new Vue({
        el: '#app',
        data: {
            list: []
        },
        created() {
            this.loadComments();
        },
        methods: {
            loadComments() {//從本地的localStorage中加載評論列表
                let list = JSON.parse(localStorage.getItem('cmts') || '[]');
                this.list = list;
            }
        },
        components: {
            'cmt-box': commentBox
        }
    })
</script>

</body>
</html>

四、使用ref獲取dom元素和組件

<div id="app">
    <input type="button" value="獲取元素" @click="getElement">

    <h3 ref="myh3">哈哈哈,今天天氣太好了!</h3>

    <hr>

    <login ref="mylogin"></login>
</div>

<script>

    var login = {
        template: '<h1>登錄組件</h1>',
        data() {
            return {
                msg: 'son msg'
            }
        },
        methods: {
            show() {
                console.log('調(diào)用了子組件的方法');
            }
        }
    };

    var vm = new Vue({
        el: '#app',
        data: {},
        methods: {
            getElement() {
                //ref是英文單詞reference 引用的意思
                console.log(this.$refs.mylogin.msg);
                this.$refs.mylogin.show();
            }
        },
        components: {
            login
        }
    })
</script>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容