父组件向子传值:
1. 把要传递给子组件的数据,作为自定义属性 通过 v-bind 将父组件的数据绑定在要使用该数据的子组件标签上
<par :mag="message"></par>
2. 子组件不能直接使用父组件传递过来的数据,可以通过 props 接受子组件的属性从而拿到属性值,之后可以在页面中直接使用该属性来渲染属性值;(props 写在定义的组件模版中)
props: ['mag']
3. 在接受父组件传递过来的 props 的数据的时候,接受的名称 必须要和父组件传递过来的自定义属性名称保持一致!
props的值可以是一个数组 ,它里面可以是该组件所有属性的集合
<!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="./js/vue.js"></script>
</head>
<body>
<div id="app">
<par :mag="message"></par> <!--可以通过自定义属性将父组件的数据绑定在要使用该数据的子组件标签上-->
</div>
<script>
var par = {
template:`
<div>测试父子组件传值--》{{ mag }}</div>
`,
props: ['mag'] // 用props来接受子组件的属性
}
var vm=new Vue({
el:'#app',
data:{
message: '能否成功' // 父组件中的数据
},
methods:{},
components:{ // 注册局部组件
par
}
});
</script>
</body>
</html>