父组件修改子组件data数据 以及 父组件调用子组件定义的方法 —— ref
子组件:
<template>
<div class="keyboard-wrapper" :class="isShow"></div>
</template>
<script>
export default {
data() {
return {
isShow:"hide"
}
},
methods: {
cutdown() {
alert(1)
}
}
}
</script>
父组件:
<template>
<Child ref="child"></Child >
</template>
<script>
import Child from "./child"
export default {
components: {
Child
},
methods: {
changeChildData() {
this.$refs.child.isShow = "show"; //修改子组件isShow的值
this.$refs.child.cutdown(); //调用组组件cutdown方法
}
}
}
</script>
父组件引用子组件后,在子组件上添加 ref 属性,通过 this.$refs 的方式,父组件可以修改子组件任意data数据.
当然这种方式还可以调用子组件的方法:this.$refs.child.cutdown();
父组件修改子组件中的data数据 —— props
子组件
<template>
<div>{{title}}</div>
</template>
<script>
export default {
props: ['title']
}
</script>
父组件
<template>
<Child :title="title"></Child >
</template>
<script>
import Child from "./child"
export default {
data() {
return {
title: "这是父组件定义的title"
}
},
components: {
Child
},
}
</script>
父组件引用子组件后,在子组件上绑定要传的值,例如我们需要修改子组件的title,那我们就绑定title,然后在父组件添加一个data数据改变子组件的title值,子组件通过props的方式接收这个值;
子组件向父组件传递数据 —— $emit
子组件
<template>
<div class="keyboard-wrapper" :class="isShow"></div>
</template>
<script>
export default {
data() {
return {
isShow:"hide"
}
},
methods: {
cutdown() {
this.isShow = "hide"
this.$emit('trans', "hide")
}
}
}
</script>
父组件
<template>
<Child @trans="hideMask"></Child >
</template>
<script>
import Child from "./child"
export default {
components: {
isShow
},
methods: {
hideMask(msg) {
this.isShow = msg; //msg为子组件传递的数据“hide”
}
}
}
</script>
在子组件中通过this.$emit(参数一,参数二)的方法将参数二通过参数一为事件传递给父组件,父组件中在注册的子组件上通过 @参数一=“自定义事件” 的方式在自定义事件中获取到传递的数据参数二;
更新data中的数组数据Dom不会重新渲染解决办法
<template>
<div v-for="item in codeList">{{item}}</div>
</template>
<script>
export default {
data() {
return {
codeList:[]
}
}
methods: {
updateList() {
for(var i = 0; i < this.codeList.length; i++){
if(this.codeList[i] == ""){
this.$set(this.codeList, i, "项目"+i);
}
}
}
}
}
</script>
我们需要通过this.$set方法更新data中的数组数据,这样页面才会同步渲染dom