在子组件定义个函数

    1. //孙子组件
    2. <template>
    3. <div>
    4. <div>我是孙子组件</div>
    5. <button @click="transformDataTo">点击传递数据给爷爷组件</button>
    6. </div>
    7. </template>
    8. <script>
    9. export default {
    10. name: "",
    11. data() {
    12. return { msg: "wo is wangsu" };
    13. },
    14. mounted() {},
    15. components: {},
    16. methods: {
    17. dispatch(eventName, data) {
    18. let parent = this.$parent;
    19. while (parent) {
    20. if (parent) {
    21. parent.$emit(eventName, data);
    22. parent = parent.$parent;
    23. } else {
    24. break;
    25. }
    26. }
    27. },
    28. transformDataTo() {
    29. this.dispatch("inputs", this.msg);
    30. },
    31. },
    32. };
    33. </script>
    34. <style></style>
    1. //子组件
    2. <template>
    3. <div>
    4. <div></div>
    5. <Hello />
    6. </div>
    7. </template>
    8. <script>
    9. import Hello from "./Hello.vue";
    10. export default {
    11. name: "",
    12. data() {
    13. return {};
    14. },
    15. methods: {},
    16. components: {
    17. Hello,
    18. },
    19. };
    20. </script>
    21. <style></style>
    1. //父组件
    2. <template>
    3. <div>
    4. <Mine @inputs="change" />
    5. <h1>{{msg}}</h1>
    6. </div>
    7. </template>
    8. <script>
    9. import Mine from "./components/Mine.vue";
    10. export default {
    11. name: "App",
    12. data() {
    13. return {
    14. msg: "",
    15. };
    16. },
    17. components: {
    18. Mine,
    19. },
    20. methods: {
    21. change(msg) {
    22. this.msg = msg;
    23. },
    24. },
    25. };
    26. </script>
    27. <style></style>