父传子
父组件
<template> <div> <!-- 通过给子组件自定义属性和事件来传递数据 --> <son :fatherAge="age" @fatherMethod="log"></son> </div> </template> <script> import son from ‘./son.vue‘ export default { name: ‘father‘, data() { return { age: 999 } }, methods: { log() { console.log(1) } }, components: { son } } </script>
子组件
<template> <div> <!-- 使用父组件传递的数据或方法时,用的是自定义的属性名,建议使用与变量相同的名称,方便使用 --> <p>{{ fatherAge }}</p> <button @click="useFatherMethod">CLICK</button> </div> </template> <script> export default { // props设置获取哪些父组件传递的变量,Number指获取的变量必须为数字型,否则报错 props: { fatherAge: Number }, methods: { // 方法不需要设置props,直接使用$emit方法调用父组件方法 useFatherMethod() { this.$emit(‘fatherMethod‘) } }, } </script>
子传父
子组件利用父组件方法,将参数传递
父组件
<template> <div>
<!-- 类似vuex,利用自身方法修改自身的数据,以达到传递数据的目的 --> <p>father: {{ fatherAge }}</p> <son @fatherMethod="changeAge"></son> </div> </template> <script> import son from ‘./son.vue‘ export default { name: ‘father‘, data() { return { fatherAge: 999 } }, methods: { changeAge(sonAge) { this.fatherAge = sonAge } }, components: { son } } </script>
子组件
<template> <div> <p>sonAge: {{ sonAge }}</p> <button @click="useFatherMethod">CLICK</button> </div> </template> <script> export default { data() { return { sonAge: -999 } }, methods: { // 调用父组件方法时,第一个参数是监听的事件名,后面的是事件方法的参数 useFatherMethod() { this.$emit(‘fatherMethod‘, this.sonAge) } }, } </script>
子传子
晚点写
原文:https://www.cnblogs.com/xijiang/p/14510815.html