首页 > 其他 > 详细

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

时间:2019-06-27 14:34:41      阅读:111      评论:0      收藏:0      [点我收藏+]
子组件获取父组件传递的数据通常是通过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>

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

原文:https://www.cnblogs.com/zhx119/p/11096643.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!