vue基礎父子組件輸入動態傳值

在學習vue2.x的時候,遇到了一個問題,就是父子組件如何傳遞動態輸入的值,文檔介紹都是傳遞固定值的,比如我想傳遞一個剛輸入的值呢,子組件如何顯示?一下就是簡單的代碼:

注:本人使用的是官方的腳手架學習的,可以通過父級組件向子級組件傳遞動態輸入的值。然後本人重寫了一個測試頁面,直接複製代碼就可以運行的(看懂以下代碼,父子組件傳遞原理也是一樣的,此處以對象爲例):

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>父組件向子組件動態傳值示例</title>
    <!-- 導入官方cdn的vue文件-->
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>

</head>

<body>
    <div id="app">
        <ul>
            <li v-for="item in items">
                {{item}}
            </li>
        </ul>
        <p>添加一個列表項:
            <input type="text" v-model="newItem" v-on:keyup.enter='addNew()' placeholder="按回車鍵提交">
        </p>
        <p>顯示輸入框傳遞給子組件的添加內容(對象):</p>

        <!-- 注意這個傳遞的參數值必須前面有:v-bind:組件獲取的變量名='需要傳遞的變量名' 或 :組件獲取的變量名='需要傳遞的變量名'  ,否則傳遞的永遠是字符串的值-->
        <!-- 這種方式傳遞的是字符串 -->
        <!-- <component-a msg1childtofather='msgchildtofather'></component-a> -->
        <!-- 以下兩種方式都是傳遞對象 -->
        <component-a :msg1childtofather='msgchildtofather'></component-a>
        <!-- <component-a v-bind:msg1childtofather='msgchildtofather'></component-a> -->

    </div>
</body>

<script>
    Vue.component('component-a', {
        props: ['msg1childtofather'],
        template: '<h2 v-text=\'msg1childtofather\'></h2>',
        methods: {
            output: function () {
                alert('You click button! and submit value:' + this.msg1childtofather);
            }
        }
    })

    new Vue({
        el: "#app",
        data: {
            items: [],
            newItem: "",
            msgchildtofather: ""
        },
        methods: {
            addNew: function () {
                // 使用v-model和ul li input向數組items添加一個動態項內容,注意添加數組格式
                this.items.push(this.newItem);
                // 測試傳遞動態添加對象值
                var childfather = {
                    label: this.newItem,
                    label2: '默認值'
                };
                this.msgchildtofather = childfather;

                this.newItem = "";
            }
        },
    })
</script>

</html>

測試結果如下:
默認界面

輸入結果頁面

發佈了38 篇原創文章 · 獲贊 56 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章