<input v-model="parentData"> //等同於 <input :value="parentData" @input="parentData = $event.target.value" >
demo
<div id="app"> <runoob-input v-model="num"></runoob-input> <p>輸入的數字為:{{num}}</p> </div> <script> Vue.component('runoob-input', { template: ` <p> <!-- 包含了名為 input 的事件 --> <input ref="input" :value="value" @input="$emit('input', $event.target.value)" > </p> `, props: ['value'], // 名為 value 的 prop }) new Vue({ el: '#app', data: { num: 100, } }) </script>
一個組件上的 v-model 默認會利用名為 value 的 prop 和名為 input 的事件,但是像單選框、復選框等類型的輸入控件可能會將 value attribute 用於不同的目的。model 選項可以用來避免這樣的沖突 Vue.component('base-checkbox', { model: { prop: 'checked', event: 'change' }, props: { checked: Boolean }, template: ` <input type="checkbox" v-bind:checked="checked" v-on:change="$emit('change', $event.target.checked)" > ` })
而.sync修飾符類似於v-mode,其實就相當於一個語法糖
<comp :foo.sync="bar"></comp> //等同於 <comp :foo="bar" @update:foo="val => bar = val"></comp>
調用:this.$emit('update:foo', newValue)
demo
<template> <div class="details"> <myComponent :show.sync='valueChild' style="padding: 30px 20px 30px 5px;border:1px solid #ddd;margin-bottom: 10px;"></myComponent> <button @click="changeValue">toggle</button> </div> </template> <script> import Vue from 'vue' Vue.component('myComponent', { template: `<div v-if="show"> <p>默認初始值是{{show}},所以是顯示的</p> <button @click.stop="closeDiv">關閉</button> </div>`, props:['show'], methods: { closeDiv() { this.$emit('update:show', false); //觸發 input 事件,並傳入新值 } } }) export default{ data(){ return{ valueChild:true, } }, methods:{ changeValue(){ this.valueChild = !this.valueChild } } } </script>