一、props
1.父组件属性传值
<cu-childern title="hello word" msg="parent"/>
2.子组件接收
2.1.1 props接收方式
props:{
title:{
type: String, //类型
default: "" //默认值
},
msg:{
type: String, //类型
default: "" //默认值
}
}
2.1.2 attrs获取值
mounted() {
console.log(this.$attrs) //即可拿到
}
3.子组件可通过this.$emit('title',[{title:'这是title'}])传递方法给父组件
二、provide 和 inject
注意:provide 和 inject 绑定并不是可响应的, 适用于高阶插件,不推荐直接用于业务代码
1.父组件声明传递的数据
provide:{
msg: "hello word",
handelEvent:()=> console.log('click event') //传递事件
}
2.子孙组件使用
inject:['msg','handelEvent']
mounted(){
console.log(this.msg)
this.handelEvent
}
三、children or parent
1.子组件获取父组件属性和方法,只能拿到一级的数据,并且不是响应式
//子组件
mounted(){
console.log(this.$parent)
}
2.父组件获取子组件属性和方法,只能拿到一级的数据,并且不是响应式
mounted(){
console.log(this.$children)// 返回是数组,父组件可能存在多个子组件
}
四、$refs or $root
1. $refs获取子组件属性方法,如果ref绑定在html标签元素上则返回该dom节点
1.1 父组件中
<cu-childern ref="childrenref"/>
mounted(){ console.log(this.$refs.childrenref) }//拿到属性和方法
2. $root 该方法返回根节点属性
mounted(){
console.log(this.$root) //获取根实例,最后所有组件都是挂载到根实例上
console.log(this.$root.$children[0]) //获取根实例的一级子组件
console.log(this.$root.$children[0].$children[0]) //获取根实例的二级子组件
}
五、vuex
state:定义存贮数据的仓库 ,可通过this.$store.state 或mapState访问
getter:获取 store 值,可认为是 store 的计算属性,可通过this.$store.getter 或
mapGetters访问
mutation:同步改变 store 值,为什么会设计成同步,因为mutation是直接改变 store 值,
vue 对操作进行了记录,如果是异步无法追踪改变.可通过mapMutations调用
action:异步调用函数执行mutation,进而改变 store 值,可通过 this.$dispatch或mapActions
访问
modules:模块,如果状态过多,可以拆分成模块,最后在入口引入
六、 listeners
1.父组件绑定方法
<cu-childern @click="handelclick"/>
2.子组件调用父组件方法
mounted(){
this.$listeners.click
}
七、EventBus
eventBus原理就是利用和emit 并实例化一个全局 vue 实现数据共享
//main.js
Vue.prototype.$bus=new Vue()
//传值组件
this.$bus.$emit('eventTarget','值')
//接收组件
this.$bus.$on('eventTarget',value=> console.log(value))
八、Vue.observable创建响应式对象
1.创建store文件
import Vue from 'vue'
export const store= Vue.observable({
token:"",
userinfo:{},
msg:"hello word"
})
export const mutations ={
setToken(token){
store.token= token
}
}
2.组件使用
2-1 引入store
import { store, mutations } from '../store'
computed: {
userinfo() {
return store.userinfo
}
},
methods: {
setToken(){
mutations.setToken(token)
}
}
九、mixins
mixins 混入
1. 创建文件
const mixin = {
created(){},
data:()=>(),
methods: {},
...
}
export default mixin
main.js
import mixin from './mixin'
Vue.mixin(mixin)
十、sync 方式修改父组件值
1.父组件使用关键字 sync
<cu-asyncchildren :title.sync="title" />
2.子组件触发update方法修改父组件值
<button @click="$emit('update:title','new sync value')">click sync</button>