Vue组件-父子组件方法传递
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>48-Vue组件-父子组件方法传递</title>
<script src="js/vue.js"></script>
</head>
<body>
<!--
1.父子组件方法传递?
在Vue中子组件是不能访问父组件的方法的,
如果子组件想要访问父组件的方法, 必须通过父组件传递
2.如何传递方法
2.1在父组件中通过v-on传递方法
传递格式 v-on:自定义接收名称 = "要传递方法"
2.2在子组件中自定义一个方法
2.3在自定义方法中通过 this.$emit('自定义接收名称');触发传递过来的方法
-->
<!--这里就是MVVM中的View-->
<div id="app">
<father></father>
</div>
<template id="father">
<div>
<button @click="say">我是按钮</button>
<!--这里通过parentsay将父组件的say方法传递给了子组件-->
<son @parentsay="say"></son>
</div>
</template>
<template id="son">
<div>
<button @click="sonFn">我是按钮</button>
</div>
</template>
<script>
// 父组件
Vue.component("father", {
template: "#father",
methods: {
say(){
alert("www.it666.com");
}
},
// 子组件
components: {
"son": {
template: "#son",
/*
注意点: 和传递数据不同, 如果传递的是方法, 那么在子组件中不需要接收
如果传递的是方法, 那么需要在子组件中自定义一个方法
如果传递的是方法, 那么在子组件中直接使用自定义的方法即可
如果传递的是方法, 那么需要在子组件自定义的方法中通过
this.$emit("自定义接收的名称")的方法来触发父组件传递过来的方法
* */
// props: ["parentsay"]
methods: {
sonFn(){
this.$emit("parentsay");
}
}
}
}
});
// 这里就是MVVM中的View Model
let vue = new Vue({
el: '#app',
// 这里就是MVVM中的Model
data: {
},
// 专门用于存储监听事件回调函数
methods: {
},
// 专门用于定义计算属性的
computed: {
},
// 专门用于定义局部组件的
components: {
}
});
</script>
</body>
</html> << 上一篇
下一篇 >>