This repository has been archived by the owner on May 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
7-子组件向父组件传值.html
57 lines (54 loc) · 1.93 KB
/
7-子组件向父组件传值.html
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
53
54
55
56
57
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="./lib/vue.js"></script>
</head>
<body>
<div id="app">
<div :style="{fontSize: font+'px'}">{{msg}}</div>
<!-- $event 接收参数,是固定值 -->
<list-item :fruits="fruits" @enlarge-text="font+=$event"></list-item>
</div>
<script>
// 子组件向父组件传值方法
// 1. props 传值原则:单向数据流(只允许父向子传值,不允许子直接操作父)
// 不应该通过props来操作父组件的数据
// 2. 在子组件template中使用$emit()来指定处理函数,向上父组件监听指定函数
// 这种方式比较好;
// 3. 使用携带参数,在子组件template中写参数,父组件中写就需要$event来接收
Vue.component("list-item", {
props: ["fruits"],
data: function() {
return {
msg: "子组件数据",
};
},
template: `
<div>
<ul>
<li v-for="item in fruits">
{{item}}
</li>
</ul>
<button @click="fruits.push('lemon')">添加</button>
<!-- $emit是固定的 带参数就在后面加上参数 -->
<button @click="$emit('enlarge-text', 20)">扩大父组件中的字体大小</button>
</div>
`,
});
const vm = new Vue({
el: "#app",
data: {
font: 12,
msg: "父组件内容",
fruits: ["apple", "orange"],
},
methods: {},
});
</script>
</body>
</html>