Vue 子组件修改prop的值


实现方法1

子组件调用父组件方法实现参数更新

父组件

<template>
  <child-component :num="num" @updateNum="updateNum"></child-component>
</template>

<script>
import childComponent from './component/child'
export default {
      
      
  components: {
      
       childComponent },
  data() {
      
      
    return {
      
      
      num: 2
  	}
  },
  methods: {
      
      
    updateNum(num) {
      
      
      this.num = num
  }
}
</script>

子组件

<template>
  <div>
    <p>父组件传过来的值:{
   
   { num }}</p>
    <button @click="changeNum">加一</button>
  </div>
</template>

<script>
export default {
      
      
  name: 'child',
  props: {
      
      
    num: {
      
      
      type:Number,
      default: 0
    }
  },
  methods:{
      
      
    changeNum() {
      
      
      this.$emit("updateNum", this.num + 1)
    }
  }
}
</script>

实现方法2

通过 .sync 修饰符以及 $emit 配合 update: 实现

父组件

<template>
  <child-component :num.sync="num"></child-component>
</template>

<script>
  import childComponent from './component/child'
  export default {
      
      
    components: {
      
       childComponent },
    data() {
      
      
      return {
      
      
        num: 2
      }
    }
  }
</script>

子组件

<template>
  <div>
    <p>父组件传过来的值:{
   
   { num }}</p>
    <button @click="changeNum">加一</button>
  </div>
</template>

<script>
  export default {
      
      
    name: 'child',
    props: {
      
      
      num: {
      
      
        type: Number,
        default: 0
      }
    },
    methods:{
      
      
      changeNum() {
      
      
        this.$emit("update:num", this.num + 1)
      }
    }
  }
</script>

猜你喜欢

转载自blog.csdn.net/xiaohuihui1400/article/details/131924450
今日推荐