组件间传值:
- 父传子通过props:
//子组件
<template>
<div class="hello">
<h1>子组件:{{title}}</h1>
</div>
</template>
//定义一个props
components: {
HelloWorld
},
props: ['title'],
// 父组件 传递数据
<HelloWorld :title="newMsg"/>
data(){
return{
newMsg:'父级data'
}
},
- 子传父自定义事件:
// 子组件
data() {
return {
name:'hello',
age:18
}
},
methods: {
submit() {
this.$emit("sendEventToParent", this.name,this.age);
}
},
//触发
created() {
this.submit()
},
// 父组件
<HelloWorld @sendEventToParent="doSomething" />
data(){
return{
msg:'',
msg2:''
}
},
methods:{
doSomething(name,age){
this.msg = name
this.msg2 = age
}
}
- 访问子组件 ref:
//父组件
<HelloWorld ref="childcom" />
mounted(){
console.log(this.$refs.childcom,'2222')
console.log(this.$refs.childcom.age,'2222')
}
- 组件通信之$bus
Vue.prototype.$bus = new Vue();
组件a
destroyed()() {
this.$bus.$emit("handels",1)
}
组件b
created() {
this.$bus.$on("handels", (res) => {
console.log(res);
});
}
beforeDestroy() {
// 在组件销毁之前清除自定义事件
this.$bus.$off("handels");
},
注意事项,参考下列链接
链接:https://blog.csdn.net/u010007013/article/details/89515208
- 缓存取值如localstorage
- 另外 p a r e n t 、 parent、 parent、children、$root,也可以访问父子组件的数据
- vuex
- 动态路由传值