vue父子传值

App.vue
<template>
  <div id="app">
    <img src="./assets/logo.png" />
    <!-- <router-view /> -->
    <father />
  </div>
</template>
 

<script>
import father from "./components/father";
export default {
  name: "App",
  components: { father }
};
</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>
 
father.vue
<template>
  <div>
    我是父类:{{message}}
    <br />
    子类传来的值:{{sendSonMessage}}
    <hr />
    <Son :toSonData="toSonData1" @toFatherData="sendSonData"></Son>
  //子向父传参 toFatherData在子类this.$emit调用并用sendSonData接收参数 </div> </template> <script> import Son from "./Son"; export default { data() { return { message: "子类你好", toSonData1: { name: "xulei", value:"18" }, sendSonMessage: "" }; }, components: { Son }, methods: { sendSonData(data) { this.sendSonMessage = data; } } }; </script>
Son.vue
<template>
  <div>
    我是子类:{{message}}
    <br />
   父类传过来的值
    {{toSonData.name}}
    {{toSonData.value}}
    <br />
    <button @click="toFatherData">点击此按钮给父类传值</button>
  </div>
</template>
 
<script>
export default {
  //  props:["toSonData"],//第一种方式
  props: {
    //第二种方式
    toSonData: {
      type: String,
      default: function() {
        return "";
      }
    }
  },
  data() {
    return {
      message: "父类你好",
      name:{name:"大哥",age:"18"}
    
    };
  },
  methods: {
    toFatherData() {
      this.$emit("toFatherData", this.name);
    }
  }
};
</script>
原文地址:https://www.cnblogs.com/lovetl/p/11913056.html