随笔都是学习笔记
随笔仅供参考,为避免笔记中可能出现的错误误导他人,请勿转载。

首先有两个组件:

  父组件:App.vue

  子组件:ComponentForOne.vue

<template>
  <img alt="Vue logo" src="./assets/logo.png">
  <!-- 下面使用组件:组件标签名 -->
  <ComponentForOne @onEvent="getCpData" :title="msg" :age="age" :arr="arr"/>
</template>

<script>
// 此处引入组件 import 组件标签名 from 组件所在位置 
import ComponentForOne from './components/ComponentForOne.vue';

export default {
  name: 'App',
  components: {
    // 挂载组件
    ComponentForOne
  },
  methods:{
    getCpData(data){
      this.arr[2]=data
    }
  },
  data(){
    return{
      msg:"App中的msg",
      age:12,
      arr:["1","2","3"]
    }
  }
}
</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>
<template>
    <h1>Here is ComponentForOne!!</h1>
    <p>{{title}}</p>
    <p>age = {{age}}</p>
    <ul style="background-color:aqua">
        <li v-for="(item,index) in arr" :key="index">{{item}}</li>
    </ul>
    <p>将数据从自定义组件传递给App.vue</p>
    <button @click="sendApp">给app.vue</button>
</template>

<script>
// 导出
export default{
// 当前组件的名称,在导入使用时需要用到
name:"ComponentForOne",
data(){
    return{
        msg:"给App.vue"
    }
},
methods:{
    sendApp(){
        // 参数1:字符串,理论上是自定义字符串,但是需要有一定意义
        // 参数2:传递的数据
        this.$emit("onEvent",this.msg)
    }
},
// 通过props在组件间传递参数
props:{
    title:{
        type:String,
        default:""
    },
    age:{
        type:Number,
        default:20
    },
    arr:{
        type:Array,
        // 数组和对象必须使用函数返回
        default:function(){
            return []
        }
    }
}
}
</script>
<!-- scoped :如果添加了此属性,表示只在当前组件中生效 -->
<style scoped>
h1{
    color: aqua;
}
</style>

首先在子组件创建一个按钮和对应的点击事件 sendApp ,然后将点击事件写入methods:

事件内容就是 this.$emit("onEvent",this.msg),给父组件提供一个名为 onEvent 的事件该事件包含值 msg

然后父组件使用这个事件,并使用这个事件中的值:

 

 

 

 看看效果:

  点击之前:

 

点击之后:

 

 那么值就成功地从子组件传递到了父组件

 

posted on 2022-11-14 14:19  时间完全不够用啊  阅读(388)  评论(0编辑  收藏  举报