一、父传子
1. 将需要传入的值绑定在子组件的标签上
<div id="app">
<ul>
<li v-for="(student,key) in students">
<!-- 将需要传入的数据绑定带子组件标签上 -->
<p-ele :student="student"></p-ele>
</li>
</ul>
</div>
2. 定义注册子组件,将传入的值用props
接收
// 注册组件
Vue.component("p-ele", {
data: function(){
return {}
},
methods: {},
props: ['student'],
template: `<p>{{student.id}} {{student.name}} {{student.age}}</p>`
})
3. Vue实例化,绑定标签
new Vue({
el: "#app",
data: {
students: [
{ id: "1001", name: "张三", age: 20 },
{ id: "1002", name: "李四", age: 18 }
]
}
})
4. 全部代码
<body>
<div id="app">
<ul>
<li v-for="(student,key) in students">
<!-- 将需要传入的数据绑定带子组件标签上 -->
<p-ele :student="student"></p-ele>
</li>
</ul>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
// 注册组件
Vue.component("p-ele", {
data: function(){
return{}
},
methods: {},
props: ['student'],
template: `<p>{{student.id}} {{student.name}} {{student.age}}</p>`
})
new Vue({
el: "#app",
data: {
students: [
{ id: "1001", name: "张三", age: 20 },
{ id: "1002", name: "李四", age: 18 }
]
}
})
</script>
</body>
二、 子传父
1. 在子组件的标签处去绑定一个自定义事件
<div id="app">
<!-- 在子组件使用处,去绑定一个this.$emit提交的事件 -->
<btn-ele @show="onReceive"></btn-ele>
{{farNum}}
</div>
2. 子组件中去绑定一个事件,在事件中,通过$emit()触发事件
vm.$emit('事件名',100)
// 注册组件件
Vue.component("btn-ele", {
data: function() {
return {
num: 200
}
},
// 在子组件的按钮上面绑定一个点击事件
template: `<button @click='showNum'>点击向父组件传参</button>`,
methods: {
showNum: function(){
// console.log("num>", this.num);
// 在子组件点击事件里面通过$emit将数据提交到子组件的标签上
// $emit() 方法有两个参数,第一个是标签处绑定的事件名,第二个是需要传输的值
this.$emit('show', this.num);
}
}
})
3. 在父组件中定义的事件接收一个参数,这个参数是子组件传过来的数据
new Vue({
el: "#app",
data: {farNum: 0},
methods: {
// 点击按钮时,也会触发该事件,事件中有个data参数,就是子组件传上来的值
onReceive(data) {
// console.log(number);
this.farNum = data
}
}
})
4. 全部代码
<body>
<div id="app">
<!-- 在子组件使用处,去绑定一个this.$emit提交的事件 -->
<btn-ele @show="onReceive"></btn-ele>
{{farNum}}
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
// 注册组件件
Vue.component("btn-ele", {
data: function() {
return {
num: 200
}
},
// 在子组件的按钮上面绑定一个点击事件
template: `<button @click='showNum'>点击向父组件传参</button>`,
methods: {
showNum: function(){
// console.log("num>", this.num);
// 在子组件点击事件里面通过$emit将数据提交到子组件的标签上
// $emit() 方法有两个参数,第一个是标签处绑定的事件名,第二个是需要传输的值
this.$emit('show', this.num);
}
}
})
new Vue({
el: "#app",
data: {farNum: 0},
methods: {
// 点击按钮时,也会触发该事件,事件中有个data参数,就是子组件传上来的值
onReceive(data) {
// console.log(number);
this.farNum = data
}
}
})
</script>
</body>