vue .sync 用法

本文介绍了Vue.js中如何使用.sync修饰符实现prop的双向绑定,通过实例展示了在不使用.sync的情况下,以及使用.sync后如何在子组件中改变父组件的值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在有些情况下,我们可能需要对一个 prop 进行“双向绑定”。也就是想实现在子组件中改变值,父组件中的值也能随着变化

 

不用sync的

父组件

<template>
  <div id="app">
    <blog :num="d" @change="d = $event"></blog>{{d}}
  </div>
</template>

<script>
import Blog from './components/Blog'

export default {
  name: 'app',
  data () {
    return {
      d:1
    }
  },
  components: {
    Blog
  }
}

</script>

<style>
@import "assets/css/base.css";
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

子组件

<template>
  <button @click="fn">{{cur}}</button>
</template>

<script>
  export default {
    name: "blog",
    props: ['num'],
    data(){
      return {
        cur: 1
      }
    },
    created(){
      this.cur = this.num
    },
    methods:{
      fn(){
        this.cur ++
        this.$emit('change',this.cur)
      }
    }
  }
</script>

<style scoped>

</style>

使用sync

父组件中改变这一句

<blog :num.sync="d"></blog>{{d}}

子组件中改变这一句

this.$emit('update:num',this.cur)

字面意思就是父组件传入num,当子组件改变时更新这个传入的值。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值