1、子组件中某个元素绑定常规事件
2、子组件事件函数中写上this.$emit("自定义事件名称',传递的值)
3、在父组件中通过给子组件的调用上通过v-on指令绑定自定义事件,自定义时间名称与子组件中的自定义时间名称一致
4、在父组件中声明自定义函数,通过参数e来获取得到子组件传递过来的值
具体代码如下
<!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>
<!-- 导入 vue 文件 -->
<script src="js/vue-2.4.0.js"></script>
</head>
<body>
<!--
子组件传值父组件的过程:
1、子组件中某一个元素绑定常规事件
2、子组件事件函数中写上 this.$emit("自定义事件名称",传递的值)
3、在父组件中通过v-on:指令(注意不能用@)绑定自定义事件,自定义事件名称与子组件中的"自定义事件名称一致"
4、在父组件methods中声明自定义函数,通过参数e获取得到子组件传递的数值
-->
<!-- 被 vm 实例所控制的区域 -->
<div id="app">
<father v-on:send-root="getFatherData"></father>
</div>
<!-- // 父组件 -->
<template id="father">
<div>
<h1>我是父组件标题</h1>
<!-- 3、 -->
<son v-on:send-father="getChildData" v-on:sendparent="getSonData"></son>
<h5>我是父组件内容</h5>
<h6>{{name}}</h6>
<button @click="event3">我是father按钮</button>
</div>
</template>
<!-- // 子组件 -->
<template id="son">
<div>
<h1>我是子组件标题</h1>
<!-- 1、 -->
<button @mouseover="event1">蛋妞1</button>
<button @dblclick="event2">按钮2</button>
</div>
</template>
<script>
// 子组件
const son = {
template: "#son",
data () {
return {
arr: ["喜洋洋", "美羊羊"],
num: 100
}
},
methods: {
event1 () {
console.log(1111);
// 2、
this.$emit("send-father", { name: "给爸爸的值" })
},
event2 () {
this.$emit("sendparent", this.arr, this.num)
}
}
}
// 父组件
const father = {
template: "#father",
data () {
return {
name: ""
}
},
methods: {
// 4、
getChildData (e) {
console.log(e);
console.log(e.name);
this.name = e.name;
},
// 用两个参数接受
getSonData (a, b) {
console.log(a);
console.log(b);
},
event3 () {
this.$emit("send-root", 325, this.name)
}
},
components: {
son
}
}
// 创建 vm 实例对象
const vm = new Vue({
// 指定控制的区域
el: '#app',
data: {
},
methods: {
getFatherData (m, n) {
console.log(m, n);
}
},
components: {
father,
}
});
</script>
</body>
</html>