父传子:pass props | 子传父:emit事件
父传子
1:创建父组件
const vm = new Vue({
el: '#app',
data: {
parentAge:18
}
})
2:创建子组件
Vue.component('cn',{
template:`
<div>
<h3>我是子组件</h3>
<p>子组件的年龄是:{{childAge}}</p>
<p>接收父组件的年龄是{{get}}</p>
<pn></pn>
</div>
`,
data(){
return {
childAge:12
}
}
})
3:通过v-bind使父子组件产生联系
<cn :get="parentAge"></cn>
4:在子组件中通过props属性接收父组件的值
props:['get']
5:得到父组件的值
我是子组件
子组件的年龄是:12
接收父组件的年龄是18
子传父
1:创建父组件
const vm = new Vue({
el: '#app',
data: {
parentAge:18
},
methods:{
cpnClick(item){
console.log(item.id);
}
}
})
2:创建子组件
Vue.component('cn',{
template:'#cpn',
data(){
return {
list:[
{id:'0',name:'mmm'},
{id:'1',name:'jjj'},
{id:'2',name:'sss'},
{id:'3',name:'666'},
]
}
},
methods: {
itemclick(item){
this.$emit("itemclick",item);
}
},
})
<template id="cpn">
<div>
<button v-for="item in list" @click="itemclick(item)">{{item.name}}</button>
</div>
</template>
3:通过发生事件emit传入父组件
this.$emit("itemclick",item);
4:在子组件通过事件绑定,然后通过父组件函数接收
<button v-for="item in list" @click="itemclick(item)">{{item.name}}</button>
methods:{
cpnClick(item){
console.log(item.id);
}
}
父传子代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="vue.js"></script>
</head>
<body>
<div id="app">
<cn :get="parentAge"></cn>
</div>
<script>
Vue.component('cn',{
template:`
<div>
<h3>我是子组件</h3>
<p>子组件的年龄是:{{childAge}}</p>
<p>接收父组件的年龄是{{get}}</p>
<pn></pn>
</div>
`,
data(){
return {
childAge:12
}
},
props:['get']
})
const vm = new Vue({
el: '#app',
data: {
parentAge:18
}
})
</script>
</body>
</html>
子传父代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="vue.js"></script>
</head>
<body>
<div id="app">
<cn @itemclick="cpnClick"></cn>
</div>
<template id="cpn">
<div>
<button v-for="item in list" @click="itemclick(item)">{{item.name}}</button>
</div>
</template>
<script>
Vue.component('cn',{
template:'#cpn',
data(){
return {
list:[
{id:'0',name:'mmm'},
{id:'1',name:'jjj'},
{id:'2',name:'sss'},
{id:'3',name:'666'},
]
}
},
methods: {
itemclick(item){
this.$emit("itemclick",item);
}
},
})
const vm = new Vue({
el: '#app',
data: {
parentAge:18
},
methods:{
cpnClick(item){
console.log(item.id);
}
}
})
</script>
</body>
</html>