关于vue中子组件修改父组件传递过来的值

Vue子组件修改父组件属性
本文介绍如何在Vue中通过子组件修改父组件传递的属性值,利用$emit触发更新,并展示了具体实现代码示例。

子组件修改父组件传递的值,在子组件中使用$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 的更新会向下流动到子组件中,但是反过来简单类型数据则不行,引用类型不改变引用地址可以。这样会防止从子组件意外改变父级组件的状态,从而导致你的应用的数据流向难以理解。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值