子组件修改父组件传递的值,在子组件中使用$emit(‘update:props接收的属性名’,‘修改的值’)
- 父组件页面-----》list.vue:
<template>
<div class="list">
<el-button @click="toShow">显示弹框</el-button>
<!-- 3、使用子组件 -->
<EditeList :toSwitchVisible.sync="switchVisible"/>
</div>
</template>
<script>
// 1、引入子组件
import EditeList from '@/components/EditList'
export default {
name: 'List',
data(){
return {
switchVisible:false
}
},
methods:{
toShow(){
this.switchVisible=true;
}
},
components:{
// 2、注册子组件
EditeList
}
}
</script>
- 子组件页面-----》EditList.vue:
<template>
<div class="editList">
<el-dialog
title="提示"
@close="toClose"
:visible="toSwitchVisible"
width="30%"
center>
<span>需要注意的是内容是默认不居中的</span>
<span slot="footer" class="dialog-footer">
<el-button @click="toCancel">取 消</el-button>
<el-button type="primary" @click="toConfirm">确 定</el-button>
</span>
</el-dialog>
</div>
</template>
<script>
export default {
name: 'EditList',
props:{
toSwitchVisible: {
type: Boolean,
defaule: false
}
},
data(){
return {
}
},
methods:{
toClose(){
this.$emit('update:toSwitchVisible', false)
},
toCancel(){
this.$emit('update:toSwitchVisible', false)
},
toConfirm(){
this.$emit('update:toSwitchVisible', false)
}
}
}
</script>
在项目中,有时操控子组件去修改父组件传递过来的值是避免不了的,但是在vue中所有的 prop 都使得其父子 prop 之间形成了一个单向下行绑定:父级 prop 的更新会向下流动到子组件中,但是反过来简单类型数据则不行,引用类型不改变引用地址可以。这样会防止从子组件意外改变父级组件的状态,从而导致你的应用的数据流向难以理解。