1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<!DOCTYPE html>
<html lang="zh-cn">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link rel="stylesheet" type="text/css" href="./fontFace.css">
<script src="../vue2.6.js"></script>

</head>

<body>
<div id="app">
<div class="details">
<my-component :show.sync='valueChild'
style="border:1px solid #ccc;"></my-component>
<button @click="changeValue">切换状态</button>
{{valueChild}}
</div>
</div>

<script>
Vue.component('my-component', {
template: `<div v-if="show">
<p>默认初始值是{{show}},所以是显示的</p>
<button @click.stop="closeDiv">关闭</button>
</div>`,
props: ['show'],
methods: {
closeDiv() {
//触发 input 事件,并传入新值,注意,必须在要改变的值前面带上update
this.$emit('update:show', false);
}
}
})
new Vue( {
el: "#app",
data() {
return {
valueChild: true,
}
},
methods: {
changeValue() {
this.valueChild = !this.valueChild
}
}
})
</script>
</body>

</html>

通过上面案例可以看出,整个流程就是父组件通过.sync修饰符将show变量传给了子组件,show变量对应的状态值是valueChild,然后子组件props接收,子组件上的事件去触发this.$emit('update:show', false);去改变show的值,并且直接同步修改了父元素上的valueChild的状态。