vue 子组件修改props方法
vue是单向数据流,父组件通过props传值给子组件,如果在子组件中修改会报错,一般是不在子组件中修改props的,但偶尔有需要在子组件有修改props,这里介绍三种可以修改子组件props的方法。
1.父组件用sync修饰,子组件通过$emit('update:参数',值)函数去修改。在项目中通常可以用改方法关闭弹框。
<template>
//父组件
<CommonDialog
:title="dialogTitle"
:showDialog.sync="isShowDialog"
:footer="true"
:width="dialogWidth"
>
....
</CommonDialog>
</template>
//子组件 弹框是否打开props: showDialog
<el-dialog :title="title" :visible="showDialog" :show-close="false" :width="width">
<i class="el-dialog__headerbtn" @click="closeModal">
<span class="iconfont iconclose"></span>
</i>
<div class="dialog-body">
<slot></slot>
</div>
<div v-if="!footer" slot="footer" class="dialog-footer">
<slot name="footer"></slot>
</div>
</el-dialog>
//关闭弹框------子组件修改props
closeModal() {
this.$emit("update:showDialog", false);
},
2.如果props是对象,在子组件中修改props
<template>
<div class="csd-select">
<el-popover
placement="bottom"
:width="width"
:trigger="config.trigger"
:config="config"
transition="fade-in"
popper-class="casade-selector"
v-model="options_show"
>
...
</el-popover>
</div>
</template>
<script>
export default {
name: "CasadeSelector",
props: {
config: {
type: Object,
//让props默认返回
default() {
return {};
}
},
},
</script>
3.props是双向绑定的
<template>
<control v-model="deviceF"></control>
</template>
//v-model里面写上我们要传给子组件,并且还会在子组件中改变这个值
<script>
import control from '@/components/control'
export default {
name:"test",
components: {
control
},
data () {
return {
deviceF: true,
}
}
}
</script>
<template>
<div>
{{device}}
<button @click="look">改变值</button>
</div>
</template>
<script>
export default {
data () {
return {
device: this.value, //定义一下
}
},
props: ['value'],//因为想要改变device,所以device要写成value,这里是写死的
components: {
},
methods: {
look () {
this.device = !this.device
this.$emit('input', this.device) //这样this.device就会被修改;前面的input是固定写死的
}
}
}
</script>