vue 子组件接收父组件的另一种方法

子组件获取父组件传递的数据通常是通过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>
</head>
<body>
<div id="app">
<my-child :msg='msg'></my-child>
</div>
</body>
</html>
<script src="./node_modules//vue//dist//vue.min.js"></script>
<script>
let vm = new Vue({
el: '#app',
data: {
msg: 'helloword'
},
components: {
'myChild': {
props: ['msg'],
mounted() {
console.log(this.$attrs)
},
components: {
'myChildren': {
props: ['msg'],
template:
`<span>{{msg}}</span>
`
}
},
template: `<div>{{msg}}
<my-children :msg='msg'></children>
</div>`
}
}
})
</script>
也可以通过子组件的$attrs接收的父组件的数据,但是这时候传递的数据子组件中不能有props的属性,不然子组件的$attrs获得的是空对象,代码如下:
<!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>
</head>
<body>
<div id="app">
<my-child :msg='msg'></my-child>
</div>
</body>
</html>
<script src="./node_modules//vue//dist//vue.min.js"></script>
<script>
let vm = new Vue({
el: '#app',
data: {
msg: 'helloword'
},
components: {
'myChild': {
// props:['msg'],
mounted() {
console.log(this.$attrs)
},
components: {
'myChildren': {
//props:['msg'],
template:

`<span>{{this.$attrs.msg}}</span>
`
}
},
template: `<div>{{this.$attrs.msg}}
<my-children :msg='$attrs.msg'></children>
</div>`
}
}
})
</script>

猜你喜欢

转载自www.cnblogs.com/zhx119/p/11096643.html