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>
father.vue<template>
<div> 我是父类:{{message}} <br /> 子类传来的值:{{sendSonMessage}} <hr />
//父类的值变化,子类的也会变化 <Son :toSonData="toSonDataValue" @toFatherData="sendSonData"></Son>
//子向父传参 toFatherData在子类this.$emit调用并用sendSonData接收参数 </div> </template> <script> import Son from "./Son"; export default { data() { return { message: "子类你好", toSonDataValue: { name: "xulei", value:"18" }, sendSonMessage: "" }; }, components: { Son }, methods: {
//接收子类传来的值 sendSonData(data) { this.sendSonMessage = data; } } }; </script>
Son.vu<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() {
//"toFatherData"和父类@之后的值对应 @toFatherData="sendSonData">
//给父类传值
this.$emit("toFatherData", this.name);
}
}
};
</script>