其他
用大头儿子和小头爸爸举例,就讲明白 vue 中父子组件的传值? | 原力计划
The following article is from 程序猿编程 Author 扬帆向海
<html lang="en">
<head>
<meta charset="UTF-8">
<title>父组件向子组件传值</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="app">
<!-- 父组件中注册子组件 -->
<!-- 在子组件标签中添加子组件props中创建的属性, 把需要传给子组件的值赋给该属性 -->
<mycom :parent-msg='pmsg' :content='hello'></mycom>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
pmsg: '父组件中的内容',
hello: '我是父组件传过来的'
},
components: {
mycom: {
data: function () {
return {
msg: '我是子组件本身的数据'
}
},
// 子组件在props中创建一个属性,用以接收父组件传过来的值
props: ['parentMsg', 'content'],
template: '<h3>{{msg + "---" + parentMsg + "----" + content}}</h3>'
}
}
});
</script>
</body>
</html>
<div id="app">
<h3>父组件</h3>
<child @receive="handleEvent"></child>
</div>
<script>
Vue.component('child', {
template: `
<div>
<h3>子组件</h3>
<button @click="sendMessage()">发送</button>
</div>
`,
data() {
return {
}
},
methods: {
sendMessage() { // 按钮的点击事件
this.$emit("receive","父组件您好,我是子组件!") // 调用父组件传递过来的方法,并且把数据传递出去
}
}
})
var vm = new Vue({
el: '#app',
methods: {
// 定义在子组件中通过 this.$emit() 调用的方法
handleEvent(val) {
console.log("父组件收到的消息是:",val)
}
}
})
</script>
</body>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>父子组件通信</title>
<script src="js/vue.js"></script>
<style>
.father,
.son {
width: 150px;
height: 100px;
}
.info {
color: #446ee4;
font-size: 20px;
font-size: bold;
}
.desc {
font-size: 18px;
}
.btn {
width: 100px;
float: left;
height: 40px;
font-size: 18px;
color: #fff;
font-weight: bold;
background: #446ee4;
margin-top: 15px;
}
.parent,
.child {
display: inline-block;
width: 550px;
}
</style>
</head>
<body>
<div id="app">
<div class="parent">
<img class="father" src="images/father.jpg">
<div class="info">我是小头爸爸</div>
<div v-if="msg !== ''" class="desc">小头爸爸接收到的消息:【{{msg}}】</div>
<div v-if="replyMsg !== ''" class="desc">小头爸爸回复说:【{{replyMsg}}】</div>
<button class="btn" @click="reply()">回复</button></button>
</div>
<div class="child">
<child :reply-msg="replyMsg" @listen="listenHandle($event)"></child>
</div>
</div>
<script>
Vue.component('child', {
props: {
replyMsg: {
type: String,
default: ''
}
},
template: `
<div>
<img class="son" src="images/son.jpg">
<div class="info">我是大头儿子</div>
<div v-if="msg !== ''" class="desc">大头儿子说:【{{msg}}】</div>
<div v-if="replyMsg !== ''" class="desc">大头儿子接收到的消息:【{{replyMsg}}】</div>
<button class="btn" @click="say()">说话</button>
</div>
`,
data() {
return {
msg: ''
}
},
methods: {
say() {
this.msg = '小头爸爸好!'
this.$emit("listen", this.msg)
}
}
})
var vm = new Vue({
el: '#app',
data() {
return {
msg: '',
replyMsg: ''
}
},
methods: {
listenHandle(val) {
this.msg = val
},
reply() {
this.replyMsg = '小头儿子好,消息已收到'
}
},
})
</script>
</body>
</html>
更多精彩推荐
☞中国最优秀的程序员都有哪些?王兴、张小龙、张一鸣是哪类?| 蒋涛说
☞秋名山老司机从上车到翻车的悲痛经历,带你深刻了解什么是 Spark on Hive!| 原力计划