- 原理:父组件将方法的引用,传递到子组件内部,子组件在内部调用父组件传递过来的方法,同时把要发送给父组件的数据,在调用方法的时候当作参数传递进去;
- 父组件将方法的引用传递给子组件,其中,
getMsg
是父组件中methods
中定义的方法名称,func
是子组件调用传递过来方法时候的方法名称
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="app">
<v-one @func="getMsg"></v-one>
</div>
<template id="temp1">
<div>
<button @click="sendMsg">向父组件传值!</button>
</div>
</template>
<script src="../vue.js"></script>
<script>
var vOne = {
template: "#temp1",
methods: {
sendMsg() {
this.$emit('func', '我是被传过来的值');
}
},
}
let vm = new Vue({
el: '#app',
methods: {
getMsg(data) {
console.log("data");
}
},
components: {
vOne
}
});
</script>
</body>
</html>