Vue中子组件向父组件传递数据的方式
Vue组件之间的关系可分为父子组件通信,兄弟组件通信,跨级组件通信。本文将具体介绍子组件向父组件传递数据的方式。
1. 自定义事件
通过自定义事件改变父组件数据
例如:
父组件:
//全局注册父组件
Vue.component("parentcom", {
data() {
return {
name: ''
}
},
template: `
<div>
<p>这是父组件</p>
// 自定义test事件,父组件触发 test事件,会触发 testHandle事件
<childcom @test="testHandle"></childcom>
//触发父组件事件时,还会将 name数据传递给父组件
<p>从子组件接收到的数据为:{{name}}</p>
</div>
`,
methods: {
testHandle(str) {
this.name = str;
}
}
});
子组件:
//全局注册子组件
Vue.component("childcom", {
data() {
return {
name: "zhangsan",
}
},
template: `
<div>
<p>这是子组件</p>
<button @click=clickHandle>click</button>
</div>
`,
methods: {
clickHandle() {
this.$emit("test", this.name)
}
}
});
2.使用v-model
通过在自定义组件上使用v-model指令
例如:
父组件:
//全局注册父组件
Vue.component("parentcom", {
data() {
return {
counter: 1
}
},
template: `
<div>
<p>这是父组件</p>
<p>{{counter}}</p>
<childcom v-model="counter"></childcom>
</div>
`
});
子组件:
//全局注册子组件
Vue.component("childcom", {
data() {
return {
counter2: 1
}
},
template: `
<div>
<button @click=clickHandle>+1</button>
</div>
`,
methods: {
clickHandle() {
this.counter2++;
this.$emit("input", this.counter2);
}
}
});
3.通过.sync修饰符
在vue@1.x使用.sync修饰符可以实现数据的双向绑定,即子组件可以修改父组件中的值。但在vue@2.0是阶段被删除了。在vue@2.3.0+ 以上版本又重新引入,它会被扩展为一个自动更新父组件属性的 v-on 监听器。就是让我们手动进行更新父组件中的值,从而使数据改动来源更加的明显。
例如:
父组件:
//全局注册父组件
Vue.component("parentcom", {
data() {
return {
counter: 1
}
},
template: `
<div>
<p>这是父组件</p>
<p>{{counter}}</p>
// 通过.sync修饰符绑定
<childcom :foo.sync="counter"></childcom>
</div>
`
});
子组件:
//全局注册子组件
Vue.component("childcom", {
data() {
return {
counter2: 1
}
},
template: `
<div>
<button @click=clickHandle>+1</button>
</div>
`,
methods: {
clickHandle() {
this.counter2++;
this.$emit("update:foo", this.counter2);
}
}
});