vue 中 v-model 和 .sync修饰符

v-model  

 1 <input v-model="searchText"> 
 2 
 3 等价于
 4 <input
 5   v-bind:value="searchText"
 6   v-on:input="searchText = $event.target.value"
 7 >
 8 当用在组件上时,v-model 则会这样:
 9 <custom-input
10   v-bind:value="searchText"
11   v-on:input="searchText = $event"
12 ></custom-input>
13 
14 Vue.component('custom-input', {
15   props: ['value'],
16   template: `
17     <input
18       v-bind:value="value"
19       v-on:input="$emit('input', $event.target.value)"
20     >
21   `
22 })
23 
24 //父组件
25  <vModel v-model="textValue"  @focus="showValue" class="username-input" placeholder="Enter your username" :a='1'></vModel>
26 //子组件
27 <template>
28         <input type="text" v-bind='$attrs' :value="value" @input="input">
29    <input :value="value" @change="change">
30 </template>
31 <script>
32   
33 inheritAttrs: false, //当在子组件中加入inheritAttrs:false时class等属性就不会自动加到根元素上了。
34  
35 // model: {
36 // //一个组件上的 v-model 默认会利用名为 value 的 prop 和名为 input 的事件,但是像单选框、复选框
37 // //等类型的输入控件可能会将 value 特性用于不同的目的。model 选项可以用来避免这样的冲突:
38 // prop: "value",
39 // event: "change"
40 // },
41   
42 props: ["value"],
43   
44 methods: {
45 input(e) {
46 this.$emit("input", e.target.value);
47 console.log(e.target.value);
48 }
49 // change(e) {
50 // this.$emit("change", e.target.value);
51 // console.log(e.target.value);
52 // }
53 },
54 
55 </script>

 

 

.sync修饰符

 1 //父组件
 2  <Sync  v-bind:title.sync="title"></Sync>   等价于       <Sync :title="title" @upDate.title = 'title=$event'></Sync>
 3 
 4 
 5 //子组件
 6 <template>
 7   <a href="javascript:void(0);" @click="changeValue">{{title}}</a>
 8 </template>
 9 <script>
10 export default {
11   props:{
12   title:{
13     default:'1',
14     type:String
15    }
16   },
17   data(){
18     return{
19 
20     }
21   },
22 methods:{
23   changeValue(){
24     this.$emit('update:title', 11111111)
25     }
26   }
27 }
28 </script>
29 <style lang="sass" scoped>
30 
31 </style>

 




  

 

posted @ 2018-09-13 11:21  崔凯通  阅读(432)  评论(0编辑  收藏  举报