Vue传值大总结
前言
一直想成为一个全栈人员,学习前端也是必备技能之一,Vue作为现在比较流行的框架,我也想学习一下,今天把Vue那些转的头晕的传值方法总结一下,以备以后查看
使用props传值
props可以用于父组件传值到子组件
//父组件
<child-label title='aaaa'></child-label>
// 子组件
export default {
props:[title,]
}
此时这个title
从父组件传到了子组件
使用$emit
// 子组件
methods:{
sendMsg(){
this.$emit('childData', 'child to parent')
}
}
// 使用父组件
<hello-vue @childData="getMsg"></hello-vue>
methods:{
getMsg(val){
this.childMsg = val
}
}
使用公共js进行传值
// 公共js
import Vue from 'vue'
export default new Vue
// 父组件
import bus from bus //引入公共的js
methods:{
sendMsg(){
bus.$emit('aaa', 'bbb')
}
}
// 子组件
import bus from bus
bus.$on('aaa')
通过 c h i l d r e n 和 children和 children和parent
一个人可以有多个孩子,但是一个孩子只能有一个父亲$children
是一个列表存储的数据通过索引获取即可
通过$attrs获取
如果和props一样传值,但是props已经使用的值,$attrs无法获取
$listensers
通过$listensers
监控$emit
数据的改变
this.$emit('childData', 'child to parent')
console.log('listensers', this.$listeners.childData)