Vue2.0的v-model指令
Vue2.0的v-model指令
v-model="属性" 写在标签中上,相当于在一个标签上,同时写了 :value='属性值' @iinput='handler' ,而handler对应的函数如果没有声明,就是给该属性值赋值的setter函数
代码一:
<!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="../js/vue.min.js"></script> </head> <body> <div id="app"> <p>总数:{{total}}</p> <!-- 在自定义组件上使用v-model指令 --> <my-component v-model="total"></my-component> </div> <div id="app1"> <p>总数:{{total}}</p> <!--第一种写法实际就是这种写法 --> <my-component @input="handleGetTotal"></my-component> </div> <script> Vue.component('my-component',{ template:'<button @click="handleClick">+1</button>', data:function(){ return { counter:0 } }, methods: { handleClick:function(){ this.counter++; this.$emit('input',this.counter); } } }); Vue.component('my-component1',{ template:'<button @click="handleClick">+1</button>', data:function(){ return { counter:0 } }, methods: { handleClick:function(){ this.counter++; this.$emit('input',this.counter); } } }); let app=new Vue({ el:"#app", data:{ total:0 } }); let app1=new Vue({ el:"#app1", data:{ total:0 }, methods:{ handleGetTotal:function(total){ this.total=total; } } }); </script> </body> </html>
代码二:
<!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="../js/vue.min.js"></script> </head> <body> <div id="app"> <p>总数:{{total}}</p> <!-- 在自定义组件上使用v-model指令 --> <my-component v-model="total"></my-component> </div> <div id="app1"> <p>总数:{{total}}</p> <!--第一种写法实际就是这种写法 --> <my-component @input="handleGetTotal"></my-component> </div> <script> Vue.component('my-component2',{ props:['value'],//? // 接收一个value属性,在有新的value时触发input事件 template:'<input :value="value" @input="updateValue">', methods: { updateValue:function(event){ this.$emit('input',event.target.value); } } }); Vue.component('my-component3',{ props:['value'],//? // 接收一个value属性,在有新的value时触发input事件 template:'<input :value="value" @input="updateValue">', methods: { updateValue:function(event){ this.$emit('input',event.target.value); } } }); let app2=new Vue({ el:"#app2", data:{ total:0 }, methods:{ handleReduce:function(total){ this.total--; } } }); let app3=new Vue({ el:"#app3", data:{ total:0 }, methods:{ handleGetTotal:function(total){ this.total=total; }, handleReduce:function(total){ this.total--; } } }); </script> </body> </html>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~