一、父子组件的数据共享
①父 -> 子共享数据
父组件通过v-bind属性绑定向子组件共享数据。同时,子组件需要使用props接受数据。
父组件:
<my-watch :msg="message" :user="userinfo"></my-watch>
data() {
return {
message: '父传子v-bind,子接受props',
userinfo:{
name:'父v-bind',age:'子props'}
}
}
子组件:
<h3>测试父传子</h3>
<p>{
{msg}}</p>
<p>{
{user}}</p>
props: ['msg','user'],
②子 -> 父共享数据
通过自定义事件的方式:
父组件:
<h3>父组件:{
{n1FromSon}}</h3>
<my-watch :n1="n1FromSon" @n1change="getn1"></my-watch>
data() {
return {
n1FromSon: 0}},
methods: {
getn1(n1) {
this.n1FromSon = n1
}
}
子组件:
<h3>测试子传父</h3>
<h3>子组件:{
{n1}}</h3>
<button type=