7.3.2自定義組件上使用v-model

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>7.3.2自定義組件上使用v-model</title>
    <style>
    [v-cloak]{
        display: none;
    }
</style>
</head>
<body>
    <div id="app" v-cloak>
        <p>總數(shù): {{total}}</p>
        <!-- <my-component v-model="total"></my-component>無需監(jiān)聽, "v-model" 綁定數(shù)據(jù),效果同下 -->
        <my-component @input="getTotal"></my-component><!-- 監(jiān)聽自定義事件 "input" -->
        <br><br><br>
        <my-component2 v-model="total"></my-component2><!-- 接收到子組件傳遞過來的值,通過特殊的 "v-model" ,直接將傳遞過來的值賦值到 "total" ,達到數(shù)據(jù)同步 -->
        <button @click="handlerReduce">-1</button><!-- 綁定點擊一次總數(shù) -1 的事件 -->
    </div>
    <script type="text/javascript" src="/node_modules/vue/dist/vue.js"></script>
    <script type="text/javascript">
        Vue.component("my-component",{
            template: `<button @click="handleClick">+1</button>`,
            data () {
                return {
                    counter: 0
                }
            },
            methods: {
                handleClick: function () {
                    this.counter++;
                    this.$emit("input",this.counter);//這里使用特殊的 "input" 事件名稱
                }
            }
        })
        Vue.component("my-component2",{
            props: ['value'],//還沒搞明白為什么這個 "value" 是代替 "v-model" 的
            //接收一個value屬性
            template: `<input :value="value" @input="updateValue" type='number'>`,
            methods: {
                updateValue: function (event) {
                    this.$emit("input",event.target.value)//每次在輸入框更新數(shù)據(jù)的時候,將數(shù)據(jù)通過 "$emit()" 傳遞給父組件
                }//在有新的 "value" 值的時候觸發(fā)input事件并更新
            }
        })
        var vm = new Vue({
            el: "#app",
            data: {
                total: 123
            },
            methods: {
                getTotal: function (value) {
                    this.total = value;
                },
                handlerReduce: function () {
                    this.total--;
                }
            }
        })
    </script>
</body>
</html>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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