关于vue.js:P15-vue-通过自定义事件-向父组件组件传值

3次阅读

共计 1253 个字符,预计需要花费 4 分钟才能阅读完成。

子组件 Content 向 App.vue 通工自定义事件传值

  • App.vue

    <script>
    import Content from "./components/Content.vue";
    export default {data() {
        return {message: '',};
      },
      methods:{getChildMsg:function (value){console.log(value);
          this.message=value
        }
      },
      components:{Content}
    }
    
    </script>
    
    <template>
    <div>
      <!-- 拿到子组件 Content 的 msg 数据 -->
      <!-- 在父组件通过 v -on 监听自定义的子组件的自定义事件 -->
      <Content @injectMsg="getChildMsg"> </Content>
      <h2>{{message}}</h2>
    </div>
    
    </template>
    
    
  • Content.vue
<template>
  <div>
    <!-- 组件是能够复用 -->
    <Hello_kugou :message="msg" :static='56'></Hello_kugou>
    <h3>{{msg}}</h3>
    <button @click="msg=' 酷狗 '"> chagebut</button>
    <button @click="sendParent"> 提交数据给父组件 </button>

  </div>
</template>

<script>
const obj={msg:"hello---kugou"}

import Hello_kugou from "./Hello_kugou.vue";
export default {data(){// 让每一个组件对象都返回一个对象,不对数据净化
    return{
      msg: 'hellokugoumsg',
      list: [1,2,3]
    };
  },
  components:{Hello_kugou},
  methods:{
    // 在子组件理  $emit 触发事件
    sendParent:function (){//this.$emit('事件名称', '发送的事件参数')
      this.$emit('injectMsg', this.msg)
    }
  },
  name: "Content"
}
</script>

<style scoped>

</style>
  • Hello_kugou.vue
<template>
  <div>
    <h2>hello kugou</h2>
    <h2>{{message2}}-- 调用父组件的变量 </h2>

  </div>
</template>

<script>
export default {
  name: "Hello_kugou",
  //props: ['message', 'static']
  props:{
    // message: String,// 类型限度
    // static: String
    message2:{
      type:String,
      default:"nihhaokugou",
      //required:true
    },
  }
}
</script>

<style scoped>

</style>

正文完
 0