vue的父子组件传值
1. 使用props进行父传子
- 父组件在使用子组件时进行绑定传值
- 子组件使用props数组接收父组件传来的值
let comp = {
data(){
return {
}
},
/*props接收父组件的传值*/
props: [name, g],
template: `
<p>name, g</p>
`
}
new Vue({
el: "#id",
data {
name: "vue",
google: "google"
},
components: {
comp
},
template: `
<!--绑定传值-->
<comp :name = "name" :g = "google"></comp>
`
})
2. 使用事件触发进行子传父
父组件定义事件方法
子组件中的点击事件中通过$emit触发父组件的方法,从而进行传值
let comp = {
data(){
return {
id: 1;
}
},
template: `
<button @click="clickHandler"></button>
`,
methods: {
clickHandler(){
this.$emit("clickMethod", this.id)
}
}
}
new Vue({
el: "#id",
data: {
name: "vue"
},
components: {
comp
},
template: `
<comp @clickMethod = "inputValue"></comp>
`,
methods: {
inputValue(data){
console.log('父组件获取值', data);
}
}
})
3. 使用ref进行父传子
子组件使用ref注册引用
这些注册引用信息会保存在父组件的 r e f s 中 , 父 组 件 通 过 refs中,父组件通过 refs中,父组件通过refs可以获取子组件,通过调用子组件的方法进行传值
let comp = {
data(){
return {
id: 1
}
}
}
new Vue({
el: "#id",
data: {
},
components: {
comp
},
template: `
<comp ref="sonComponent"></comp>
`,
methods: {
handler(){
/*
this.$refs.sonComponent获取子组件
*/
}
}
})
4. 使用事件总线进行组件间通信
事件总线需要新建一个新的vue实例,称作bus
let bus = new Vue({});
如果组件A需要向组件B进行传值
- 在A中需要进行触发事件
- 在B中需要进行监听事件
// 组件A中
bus.$emit('事件名', data);
// 组件B中
bus.$on('事件名', function(data){/*...*/})
5. vuex
当项目越来越复杂的时候,事件总线使用则会越来越混乱,命名也会冲突,所以引入vuex
vuex是一个专门为vue.js应用程序开发的状态管理工具,它采用集中式存储管理应用的所有组件的共享状态
vuex中的state用于保存所有组件的共享状态,mutation是唯一修改state的入口,action是用于进行共享状态的异步请求的