mac_05185 2022-10-13 09:57 采纳率: 67.1%
浏览 52
已结题

vue组件自定义事件,提示ref不是一个方法

vue的组件自定义事件,提示我说this.$refs.student.$on is not a function,是哪里出现了问题

img

下面是我的app代码和student代码:

// App.vue
<template>
  <div class="app">
    <h1>{{ msg }}</h1>
    
    <School :getSchoolName="getSchoolName" />
    
    
    <hr />
    <Student ref="student" />
  </div>
  <hr />
  <img alt="Vue logo" src="./assets/logo.png" />
  <HelloWorld msg="Welcome to Your Vue.js App" />
</template>

<script>
import HelloWorld from "./components/HelloWorld.vue";
import School from "./components/School.vue";
import Student from "./components/Student.vue";

export default {
  name: "App",
  data() {
    return {
      msg: "this is hello vue",
    };
  },
  methods: {
    getSchoolName(name) {
      console.log("app 接受了学校名 ", name);
    },
    getStudentName(name) {
      console.log('app 接受了学生姓名 ', name);
    }
  },
  components: {
    HelloWorld,
    School,
    Student,
  },
  mounted() {
    setTimeout(() => {
      this.$refs.student.$on('atguigu', this.getStudentName)
    }, 20);
  },
};
</script>

<style>
.app {
  height: auto;
  width: 50%;
  background-color: blueviolet;
  padding: 10px;
}

#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>

<template>
    <div class="student">
        <h2>学生姓名:{{name}}</h2>
        <h3>学生性别: {{sex}}</h3>
        <button @click="sendStudentName">把学生给app</button>
    </div>
</template>

<script>


export default ({
    name: 'Student_vue',
    data() {
        return {
            name: 'mac',
            sex: 'man'
        }
    },
    methods: {
        sendStudentName() {
            // 触发student实例身上的硅谷事件
            this.$emit('atguigu', this.name);
        }
    }
})
</script>


<style scoped>
.student {
    background-color: teal;
    padding: 5px;
    margin-top: 10px;
}
</style>
  • 写回答

5条回答 默认 最新

  • 音药 2022-10-13 13:47
    关注

    vue3与vue2语法不一样

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(4条)

报告相同问题?

问题事件

  • 系统已结题 10月21日
  • 已采纳回答 10月13日
  • 创建了问题 10月13日

悬赏问题

  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?