vue中this.$emit(“update:xx“,value)和xx.sync的用法

在vue项目中,正常父子组件传值使用props属性,而且要注意props的单向数据流特点,也即父组件通过props向子组件传值,但子组件不能直接改props里面的值,正常的做法一般是通过$emit向父组件发射一个事件,然后传值,达到子组件想要修改父组件值的目的.vue在后面的版本为了简化写法,推出了.sync的语法糖写法,代码更简洁,达到的效果是一样的

//父组件
<template>
  <div class="home">
    {{ originStr }}
   第一种写法
  <!--  <hello-world :message="originStr" @update:message="changeMessage" />  -->
  第二种写法(.sync语法糖的写法)
 <hello-world :message.sync="originStr" />
  </div>
</template>
<script>
// @ is an alias to /src
import HelloWorld from "../components/HelloWorld.vue";

export default {
  name: "Home",
  components: {
    HelloWorld,
  },
  data() {
    return {
      originStr: "你好",
    };
  },
  methods: {
    changeMessage(str) {
      console.log(str);
      this.originStr = str;
    },
  },
};
</script>

//子组件
<template>
  <div class="hello">
    <hr />
    <button @click="btnclick">兄弟点我</button>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  components: {},
  props: {
    message: {
      type: String,
      default: "",
    },
  },
  methods: {
    btnclick() {
      console.log("触发了事件");
      this.$emit("update:message", "Hello World");
    },
  },
};
</script>

<style scoped lang="scss"></style>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值