Vue的使用--输入框数据的双向绑定

使用

  1. 在html文件中通过以下方式引入Vue:
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  1. 开始使用

案例

实现效果

向firstName和lastName中输入内容,会同时显示到fullName,fullName2,fullName3中,其中改变fullName3的值,firstName和lastName的值也会改变

<div id="app">
    firstName:<input type="text" v-model="firstName"><br/>
    lastName:<input type="text" v-model="lastName"><br/>
    fullName(单向):<input type="text" v-model="fullName1"><br/>
    fullName2(单向):<input type="text" v-model="fullName2"><br/>
    firstName3(双向):<input type="text" v-model="fullName3"><br/>

</div>

代码

  • 起到一个数据双向绑定的作用

v-model

<script>
    new Vue({
        el: '#app',
        data(){
            return {
                firstName: '',
                lastName: '',
                fullName2: '',
            }
        },
        //使用计算属性
        computed: {
            fullName1: function(){
                /*let firstName = this.firstName
                let lastName = this.lastName*/
                return this.firstName+' '+this.lastName
            },
            fullName3: {
                get() {
                    return this.firstName+' '+this.lastName
                },
                set(value) {
                    let names = value.split(/\s+/)
                    this.firstName=names[0]
                    this.lastName=names[1]
                }
            }
        },
        //使用监听器
        watch: {
            firstName: function(newVal,oldVal){
                this.fullName2 = newVal+' '+this.lastName
            },
            lastName: function(newVal,oldVal){
                this.fullName2=this.firstName+' '+newVal
            }

        }
    })
</script>

new Vue({ })//第一步

  • 起类似选择器作用

el: ‘#app’

  • 注意Vue中的数据尽量使用以下格式
data(){
	 return{
     }
}
  • 计算属性 ,其中的值可以不在data中定义

computed: { }

  • 回调函数fullName1,当函数中的firstName和lastName发生改变时,触发函数
 fullName1: function(){
                let firstName = this.firstName
                let lastName = this.lastName
                return firstName+'  '+lastName
            }
          相当于
 fullName1:{
		get(){
		}
}
  • 当value值改变时触发函数set(value){}
fullName3: {
		set(value) {
		   
		 }
}
  • 监听器,对v-model=‘firstName’进行监听,newVal表示改变后的值,oldVal表示原来的值
 watch: {
            firstName: function(newVal,oldVal){
                this.fullName2 = newVal+' '+this.lastName
            }
        }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值