zoukankan      html  css  js  c++  java
  • 组件上使用v-model

    组件上使用v-model

    <input v-model="searchText">
    

    等价于

    <input
      v-bind:value="searchText"
      v-on:input="searchText = $event.target.value"
    >
    

    当用在组件上时,v-model则会这样:

    <custom-input v-model="searchText"></custom-input>
    

    等同于

    <custom-input
      v-bind:value="searchText"
      v-on:input="searchText = $event"
    ></custom-input>
    

    为了让它正常工作,这个组件内的<input>必须:

    • 将其 value 特性绑定到一个名叫valueprop
    • 在其 input 事件被触发时,将新的值通过自定义的input事件抛出
    Vue.component('custom-input', {
      props: ['value'],
      template: `
        <input
          v-bind:value="value"
          v-on:input="$emit('input', $event.target.value)"
        >
      `
    })
    

    现在v-model就应该可以在这个组件上完美地工作起来了:

    <custom-input v-model="searchText"></custom-input>
    

    示例

    父组件App.vue中

    <template>
      <div id="app">
        <Model v-model="searchText"></Model>
        <span>{{searchText}}</span>
        <!-- 等价于
        <custom-input
            v-bind:value="searchText"
            @input="searchText = $event"
        ></custom-input> -->
      </div>
    </template>
    <script>
    import Model from "./components/Model";
    
    export default {
      name: "App",
      data: function() {
        return {
          searchText:''
        };
      },
      components: {
        Model
      }
    };
    </script>
    

    子组件model.vue

    <template>
      <div id="app">
        <input v-bind:value="value" @input="$emit('input', $event.target.value)">
      </div>
    </template>
    <script>
    export default {
      props: ["value"],
    
    };
    </script>
    
    

    过程:
    1.输入文字
    2.:value='search' 传给子组件
    3.子组件props接收
    4.子组件:value='value'
    5.子组件绑定input通过$emit传给父组件
    6.父组件@input='searchText = $event'接收

  • 相关阅读:
    做题总结
    关于SQLSERVER中用SQL语句查询的一些个人理解
    关于SQLSERVER联合查询一点看法
    C#中怎样实现序列化和反序列化
    java内部类的使用
    C#抽象类
    匿名类
    Foreach能够循环的本质
    C#索引器
    深入了解接口的使用
  • 原文地址:https://www.cnblogs.com/guangzan/p/11269005.html
Copyright © 2011-2022 走看看