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,當子組件改變時更新這個傳入的值。

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