vue的双向绑定示例

摘自《vue.js实战》
 
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  </head>
  <body>
    <div id="app">
      <p>总数为{{total}}</p>
      <my-component v-model="total"></my-component>
      <button @click="reduce">-1</button>
    </div>
    <script>
      Vue.component("my-component", {
//子组件通过props:获取父组件的值
         props: ["value"],
        template: '<input  :value="value"  @input="handleCount">',
        methods: {
//将子组件输入框的值通过$emit传给父组件
           handleCount: function (event) {
            this.$emit("input", event.target.value);
          },
        },
      });
      var v = new Vue({
        el: "#app",
        data: {
          total: 0,
        },
        methods: {
          reduce: function () {
            this.total--;
          },
        },
      });
    </script>
  </body>
</html>

猜你喜欢

转载自www.cnblogs.com/kukai/p/12913161.html
今日推荐