手動實現vue元件間的雙向資料繫結

兩情迢迢發表於2019-02-13

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>vue</title>
  <script src="https://cdn.bootcss.com/vue/2.6.3/vue.js"></script>
</head>
<body>
  <div id="app">
  </div>
  <script>
    var temOne = {
      props:['value'],
      template: `
        <div>
          <input type="text" @input="handleInput" :value="value">
        </div>
      `,
      methods: {
        handleInput (e) {
          this.$emit('input', e.target.value)
        }
      }
    }
    var vm = new Vue({
      el: '#app',
      data: {
        value: '123'
      },
      components: {
        temOne
      },
      template: `
        <div>
          {{value}}
          <tem-one :value="value" @input="value = arguments[0]"></tem-one>
          <tem-one v-model="value"></tem-one> <!-- v-model語法糖、有點費解 -->
        </div>
      `
    })
  </script>
</body>
</html>
複製程式碼

相關文章