1. 默認(rèn)情況
v-model=“visible” 等價(jià)于 :value=“visible” 加上 @input=“visible = $event”
所以 v-model 就是父組件向子組件傳了個(gè) value 字段的值,子組件使用 props 定義 value 字段, 就可以在子組件使用 value 讀取這個(gè)值;子組件使用 $emit(‘input’,值) 就可以改變 v-model 的值
父組件
<template>
<div id="app">
<Tab v-model="visible" />
</div>
</template>
<script>
import Tab from "./components/Tab.vue"
export default {
name: "App",
data() {
return {
visible: true,
}
},
components: { Tab },
}
</script>
<style></style>
<script/>
子組件
<template>
<div v-show="value">
我是子組件文字
<button @click="$emit('input', false)">關(guān)閉</button>
</div>
</template>
<script>
export default {
props: {
value: {
type: Boolean,
default: false,
},
},
}
</script>
2. 子組件改變默認(rèn)字段名與事件
父組件
<template>
<div id="app">
<Tab v-model="visible" />
</div>
</template>
<script>
import Tab from "./components/Tab.vue"
export default {
name: "App",
data() {
return {
visible: true,
}
},
components: { Tab },
}
</script>
<style></style>
子組件
<template>
<div v-show="show">
我是子組件文字
<button @click="$emit('change', false)">關(guān)閉</button>
</div>
</template>
<script>
export default {
model: {
prop: "show",
event: "change",
},
props: {
show: {
type: Boolean,
default: false,
},
},
}
</script>
子組件定義了以下代碼就回改變默認(rèn)字段文章來源:http://www.zghlxwxcb.cn/news/detail-682733.html
model: {
prop: "show",
event: "change",
}
此時(shí),v-model=“visible” 等價(jià)于 :show=“visible” 加上 @change=“visible = $event”文章來源地址http://www.zghlxwxcb.cn/news/detail-682733.html
到了這里,關(guān)于在vue2使用v-model對組件進(jìn)行雙向綁定的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!