参考文章:https://segmentfault.com/a/1190000019208626
vue父子组件间通信可以用prop完成,跨级通信则要用attrs来实现。
1.$attrs实现跨级通信
父亲组件:
<template>
<div>
<p>father组件</p>
<p>msg1:{{msg1}}</p>
<hr>
<son1
:msg1="msg1"
:msg2='msg2'
:msg3='msg3'
:msg4='msg4'
title='一个标题'></son1>
</div>
</template>
<script>
import son1 from './son1.vue'
export default {
components:{
son1,
},
data(){
return{
msg1:'msg1',
msg2:'msg2',
msg3:'msg3',
msg4:'msg4',
}
}
}
</script>
其中,son1标签中:msg1的取值要跟下面data中的变量相对应,而title因为没有加:,所以title后面直接写一个字符串。
孩子组件:
<template>
<div>
<p>son1组件</p>
<p>msg2:{{msg2}}</p>
<p>son1的$attrs:{{$attrs}}</p>
<hr>
<son2 v-bind="$attrs"></son2>
</div>
</template>
<script>
import son2 from './son2.vue'
export default {
props:{
msg1:String,
},
components:{
son2,
}
}
</script>
在son1中,props中绑定msg1,则可以在son1中直接使用father组件中的msg1的取值,而现在son1的attrs中则会少了msg1。也就是说,如果想让father组件中的某个变量只在这个组件中使用,而不会传到后面的组件中,就需要在这个组件中用props绑定。
同时在使用son2的组件时,要加上v-bind=’$attrs’,让剩下的msg2,msg3,msg4和title能够传下去。
<template>
<div>
<p>son2组件</p>
<p>msg2:{{msg2}}</p>
<p>son2的$attrss:{{$attrs}}</p>
<hr>
<son3 v-bind="$attrs"></son3>
</div>
</template>
<script>
import son3 from './son3.vue'
export default {
props:{
msg2:String
},
components:{
son3,
}
}
</script>
<template>
<div>
<p>son3组件</p>
<p>msg3:{{msg3}}</p>
<p>title:{{title}}</p>
<p>son3:{{$attrs}}</p>
</div>
</template>
<script>
export default {
props:{
msg3:String,
title:String,
},
}
</script>
最终程序显示结果:
2.props实现父子通信
props实现父组件向下传递数据给子组件(注:组件中的数据有三种形式:data、props和computed)
3.子组件通过events给父组件发送消息
子组件:
<template>
<div>
<h1 @click="changeTitle">{{title}}</h1>
</div>
</template>
<script>
export default {
name:'son',
data(){
return{
title:"son title",
}
},
methods: {
changeTitle(){
this.$emit("titleChanged","子向父组件传值")
},
},
}
</script>
父组件:
<template>
<div>
<Son v-on:titleChanged="updateTitle"></Son>
<h2>father的title:{{title}}</h2>
</div>
</template>
<script>
import Son from './event-son.vue'
export default {
name:'father',
data(){
return{
title:'father title',
}
},
methods: {
updateTitle(e){
this.title = e;
}
},
components:{
Son,
}
}
</script>
这是传值之前的结果:
这是传值之后的结果:
4.$ emit /$on
5.vuex
Vuex实现了一个单向数据流,在全局拥有一个State存放数据,当组件要更改State中的数据时,必须通过Mutation进行,Mutation同时提供了订阅者模式供外部插件调用获取State数据的更新。而当所有异步操作(常见于调用后端接口异步获取更新数据)或批量的同步操作需要走Action,但Action也是无法直接修改State的,还是需要通过Mutation来修改State的数据。最后,根据State的变化,渲染到视图上。
vuex和localStorage
vuex是vue的状态管理器,存储的数据是响应式的。但是并不会保存起来,刷新以后就回到了初始状态。具体的做法是