步骤如下:1、在嵌套父组件中,给子组件标签设置 <v-zi @zizujian="fuzujian"></v-zi>此时的 @zizujian 给子组件用 this.$emit("zizujian",this.ttt) 传值(用$emit传值,即this.ttt 赋值给 zizujain,fuzujian函数参数msg接收)
<template id="fu">
<div>
<h2>父组件</h2>
<h2>接收子组件值:{{str}}</h2>
<hr>
<v-zi @zizujian="fuzujian"></v-zi>
</div>
</template>
2、此时的父组件 fuzujian 为函数名但不加括号,在methods里设置函数, 此时的msg就是接收的子组件的值
methods:{
fuzujian(msg){
this.str = msg
}
}
3、把值赋给父组件即可
<template id="fu">
<div>
<h2>父组件</h2>
<h2>接收子组件值:{{str}}</h2>
<hr>
<v-zi @zizujian="fuzujian"></v-zi>
</div>
</template>
完整代码如下:
<!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">
<script src="../vue.js"></script>
<title>Document</title>
</head>
<body>
<div id="app">
<h1 >子到父</h1>
<hr>
<v-fu></v-fu>
</div>
<template id="fu">
<div>
<h2>父组件</h2>
<h2>接收子组件值:{{str}}</h2>
<hr>
<v-zi @zizujian="fuzujian"></v-zi> <!--中间结合点-->
</div>
</template>
<template id="zi">
<div>
<h2>子组件</h2>
<h2>{{ttt}}</h2>
<button @click="zi()">父数据到子组件</button>
</div>
</template>
<script>
var vue = new Vue({
el:"#app",
data:{
},
components:{
"v-fu":{
template:"#fu",
data:function(){
return {
str:""
}
},
methods:{
fuzujian(msg){
console.log(msg)
this.str = msg
}
},
components:{
"v-zi":{
template:"#zi",
data:function(){
return {
ttt:"2222222"
}
},
methods:{
zi(){
this.$emit("zizujian",this.ttt)//用$emit传值,即this.ttt赋值给zizujain
}
}
}
}
}
}
})
</script>
</body>
</html>
|
|