抱歉,您的浏览器无法访问本站

本页面需要浏览器支持(启用)JavaScript


了解详情 >

父组件向子组件传值

我们可以这样理解:Vue实例就是一个父组件,而我们自定义的组件(包括全局组件、私有组件)就是子组件

【重点】需要注意的是,子组件不能直接使用父组件中的数据。父组件可以通过props属性向子组件传值

父组件向子组件传值的代码举例

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
58
59
60
61
62
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="vue2.5.16.js"></script>
</head>

<body>
<div id="app">
<!-- 第三步:父组件在引用子组件的时候, 通过 属性绑定(v-bind:)的形式, -->
<!-- 把 需要传递给 子组件的数据,以属性绑定的形式,传递到子组件内部,供子组件使用 -->
<component1 v-bind:parent-msg="msg"></component1>
</div>

<!-- 定义子组件的模板 -->
<template id="myTemplate">
<!-- 第二步:在子组件的模板中,使用props中的属性 -->
<h2 @click="change">我是子组件。我想使用父组件中的数据parentMsg: {{ parentMsg }}</h2