vue 小程序 多层嵌套-触发子组件事件问题

在小做小程序的项目中,遇到了多组件 嵌套的事情,爷-》子-》孙,遇到这种事情,网站找了好多解决方案,先用了网上的 嵌套案例:

我把这个实例分为几个步骤解读:

1、父组件的button元素绑定click事件,该事件指向notify方法
2、给子组件注册一个ref=“child”
3、父组件的notify的方法在处理时,使用了$refs.child把事件传递给子组件的parentMsg方法,同时携带着父组件中的参数msg
 4、子组件接收到父组件的事件后,调用了parentMsg方法,把接收到的msg放到message数组中

父组件

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

<template>

 <div id="app">

  <!--父组件-->

  <input v-model="msg" />

  <button v-on:click="notify">广播事件</button>

  <!--子组件-->

  <popup ref="child"></popup>

 </div>

</template>

 <script>

import popup from "@/components/popup";

export default {

 name: "app",

 data: function () {

  return {

   msg: "",

  };

 },

 components: {

  popup,

 },

 methods: {

  notify: function () {

   if (this.msg.trim()) {

    this.$refs.child.parentMsg(this.msg);

   }

  },

 },

};

</script>

 <style>

#app {

 font-family: "Avenir", Helvetica, Arial, sans-serif;

 -webkit-font-smoothing: antialiased;

 -moz-osx-font-smoothing: grayscale;

 text-align: center;

 color: #2c3e50;

 margin-top: 60px;

}

</style>

子组件

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

<template>

 <div>

  <ul>

   <li v-for="item in messages">父组件输入了:{{ item }}</li>

  </ul>

 </div>

</template>

 <style>

body {

 background-color: #ffffff;

}

</style>

 <script>

export default {

 name: "popup",

 data: function () {

  return {

   messages: [],

  };

 },

 methods: {

  parentMsg: function (msg) {

   this.messages.push(msg);

  },

 },

};

</script>

尝试了上面这种方法,只用了两层比较合适,到第三层不知道哪里问题,报错:

 最后还是没解决了这个问题,最后就是在中间(子)组件中,用了刷新整个页面的方法,具体逻辑代码如下:

vue项目实现重新加载本页面

App.vue:

<tempalte>
    <router-view v-if="isRouterAlive" />
</tempalte>

export default defineComponent({
    provide () {
      return {
        reload: this.reload
      }
    }
    data () {
        retrun {
            isRouterAlive: true
        }
    },
    methods: {
        reload () {    
            this.isRouterAlive = false
            this.$nextTick(() => {
                 this.isRouterAlive = true
            })
        }
    }
})

页面使用:

<el-button @click="reload">刷新页面</el-button>

export default {
  inject: ['reload']  
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值