鍍金池/ 問答/HTML/ vue中v-bind修飾符.sync和.once沒效果

vue中v-bind修飾符.sync和.once沒效果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>v-bind onece sync用法</title>
</head>
<body>
    <div id="example">
        <input type="text" v-model="msg">
    <child :msg.sync="msg"></child>
    </div>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue"></script>
    <script type="text/javascript">
        var child = Vue.extend({
      props: ['msg'],
      template: '<div><button v-on:click="changeChildMsg">click</button><p>{{msg}}</p></div>',
      methods: {
        changeChildMsg () {
          this.msg = 'Hello Vue!'
        }
      }
    })
    var vm = new Vue({
      el: '#example',
      data () {
        return {
          msg: 'wang wang wang!'
        }
      },
      components: {
        child: child
      }
    })
    </script>
</body>
</html>

Vue文檔說明.sync能讓子組件數(shù)據(jù)和父組件數(shù)據(jù)進(jìn)行雙向綁定。可為何當(dāng)點(diǎn)擊子組件中click按鈕后,vm.msg還是wang wang wang!

回答
編輯回答
夢(mèng)若殤

圖片描述vue2.0已經(jīng)移除v:bind的.sync和.once

2017年8月29日 11:56
編輯回答
扯機(jī)薄

vue的文檔里寫的很清楚:
從 2.3.0 起我們重新引入了 .sync 修飾符,但是這次它只是作為一個(gè)編譯時(shí)的語法糖存在。它會(huì)被擴(kuò)展為一個(gè)自動(dòng)更新父組件屬性的 v-on 監(jiān)聽器。
如下代碼
<comp :foo.sync="bar"></comp>
會(huì)被擴(kuò)展為:
<comp :foo="bar" @update:foo="val => bar = val"></comp>
當(dāng)子組件需要更新 foo 的值時(shí),它需要顯式地觸發(fā)一個(gè)更新事件:
this.$emit('update:foo', newValue)

因此你的

changeChildMsg () {
          this.msg = 'Hello Vue!'
        }

改成

changeChildMsg () {
           this.$emit('update:msg', "hello")
        }
2018年6月25日 07:36