Vue(第19篇 .sync修饰符 本文举例:子传父)

*Vue 父子组件传值在其他文章已详细介绍:https://blog.csdn.net/qq_42540989/article/details/98481824

本文介绍的是一种更加方便的写法

1、建议先看官方文档:https://cn.vuejs.org/v2/guide/components-custom-events.html#sync-%E4%BF%AE%E9%A5%B0%E7%AC%A6

2、父组件

// 父组件

 <template>
  <div class="hello">
    <son :num.sync="num"></son>
    <h1>我是父组件(接收子组件改变的值)======{{num}}</h1>
  </div>
</template>

<script>
import son from './son'
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: '我是父组件',
      num:1
    }
  },
   components: {
    son
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

3、子组件

// 子组件

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
     <button @click="change()">{{sonNum}}</button>

  </div>
</template>

<script>
export default {
  name: 'son',
  props: ['num'],
    data(){
      return {
        sonNum: 1,
        msg:'我是子组件'
      }
    },
    created(){
      this.sonNum = this.num
    },
    methods:{
      fn(){
        this.sonNum++
        this.$emit('update:num',this.sonNum);
      }
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

4、简单介绍:

      *以前prop实现双向绑定,采用的方法是:子组件向父组件发送一个事件,父组件监听到传过来的事件,然后更新prop。

       为了方便起见,我们为这种模式提供一个缩写,即 .sync 修饰符:

       ①组件内以 update:myPropName 的模式触发事件取而代之。(例如:this.$emit('update:num',this.sonNum)

       ②父组件 v-bind:value 加上.sync修饰符,即 :value.sync(例如: :num.sync="num"

6、当我们用一个对象同时设置多个 prop 的时候,也可以将这个 .sync 修饰符和 v-bind 配合使用:

// v-bind.sync="对象"

<text-document v-bind.sync="doc"></text-document>

这样会把 doc 对象中的每一个属性 (如 title) 都作为一个独立的 prop 传进去,然后各自添加用于更新的 v-on 监听器。

7、 * 例如:这是  v-bind:title.sync=”doc.title + ‘!’” 是无效的,因为带有 .sync 修饰符的 v-bind 不能和表达式一起使用。

8、 *详细介绍,官方文档中都已经说明。建议可以亲自手写实践一下,加深记忆。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值