当前位置: 代码迷 >> 综合 >> 子组件向父组件传值-$emit
  详细解决方案

子组件向父组件传值-$emit

热度:49   发布时间:2023-11-25 02:08:11.0

this.$emit()
作用:子组件向父组件传值

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>组件传值</title><script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
</head>
<body><div id="app"><v-title v-bind:title="title"></v-title><v-content v-for="(book,index) in books" v-bind:b="book" v-bind:index="index" v-on:rm="remove(index)"></v-content></div>
</body>
</html>
<script type="text/javascript">Vue.component("v-title",{
      props:["title"],template:"<h2>{
      {title}}</h2>"})Vue.component("v-content",{
      props: ["b","index"],template: "<li>{
      {b}} <button @click='re(index)'>删除</button></li>",methods:{
      re(index){
      this.$emit("rm",index);}}})let vue=new Vue({
      el:"#app",data:{
      title:"书籍",books:["Java","Python","C++"]},methods:{
      remove(index){
      this.books.splice(index,1);}}}); </script>

re函数中触发了rm事件,向父组件报告并传值,父组件发现rm事件被触发后调用vue对象的remove方法

  相关解决方案