效果:
Hello Jack !
My name is Jack ! This month is September .
<div id="app2">
<say-hello></say-hello>
<my-name :name="username"></my-name>
</div>
<script>
Vue.component("sayHello",{
template:"<h2>Hello ${this.$parent.username} !</h2>", //访问父实例(app2)数据this.$parent
delimiters:['${',"}"] //修改插值语法delimiters
});
var app2 = new Vue({
el:"#app2",
data:{
month:"September",
username:"Lily"
},
components:{
"myName":{
template:`<div><p>My name is {{ name }} !
This month is {{ this.$parent.month }} .</p>
<button @click="changeName">changeName</button></div>`, //访问父实例(app2)数据this.$parent
props:["name"],
methods:{
changeName:function () {
this.$parent.username = "Jack";
}
}
}
}
});
</script>
本文通过一个简单的示例展示了Vue.js中如何实现父子组件之间的数据传递与更新。使用了自定义事件的方式让子组件可以改变父组件的数据状态。
364

被折叠的 条评论
为什么被折叠?



