vue .sync 用法

在有些情况下,我们可能需要对一个 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,当子组件改变时更新这个传入的值。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章