使用原生的javaScript 获取节点值,和使用ref获取节点值
<template> <div> <ul> <li> 姓名:<input type="text" id="name" /> </li> <li> 年龄:<input type="text" ref="age" /> </li> </ul> <input type="button" value="提交" @click="doSubmit()" /> </div> </template> <script> export default { name: 'App', data() { return { msg: "我是一个标题" } }, methods: { doSubmit(){ // 原生javaScript var userName = document.getElementById("name").value; alert(userName); // 标签定义ref, 通过this.$refs.值.value 获取值 var userAge = this.$refs.age.value; alert(userAge); } } } </script>
vue双向数据绑定
MVVM就是我们常说的双向数据绑定,vue就是一个MVVM框架
M表示 model
V表示 view
在MVVM的框架中 model改变会影响视图view view视图改变会反过来影响model
双向数据一般用于表单中
<template> <div> <ul> <li> 姓名:<input type="text" v-model="userInfo.userName" id="name" /> </li> <li> 年龄:<input type="text" v-model="userInfo.userAge" /> </li> </ul> <input type="button" value="提交" @click="doSubmit()" /> </div> </template> <script> export default { name: 'App', data() { return { userInfo:{ userName: "张三", userAge: 20 } } }, methods: { doSubmit(){ console.log(this.userInfo); } } } </script>
单选框:radio
多选框:checkbox
下拉选择:select
的数据双向绑定:
<template> <div> <ul> <li> 姓名:<input type="text" v-model="userInfo.userName" id="name" /> </li> <li> 年龄:<input type="text" v-model="userInfo.userAge" /> </li> <li> 性别:<input name="sex" type="radio" value="1" id="sex1" v-model="userInfo.userSex" /><label for="sex1">男</label> <input name="sex" type="radio" value="2" id="sex2" v-model="userInfo.userSex" /><label for="sex2">女</label> </li> <li> 城市: <select v-model="userInfo.userCity"> <option v-for="(item, index) in cityList" :key="index" :value="item">{{item}}</option> </select> </li> <li> 爱好: <span v-for="(item,index) in userInfo.userHobby" :key="index"> <input type="checkbox" :id="'sel_'+index" v-model="item.checked"/> <label :fro="'sel_'+index">{{item.title}}</label> </span> </li> </ul> <input type="button" value="提交" @click="doSubmit()" /> </div> </template> <script> export default { name: 'App', data() { return { userInfo:{ userName: "张三", userAge: 20, userSex: 1, userCity: "北京", userHobby:[ {title: "吃饭", checked: true}, {title: "睡觉", checked: false}, {title: "吃饭", checked: false} ] }, cityList: ["北京", "上海","广州","深圳","厦门"] } }, methods: { doSubmit(){ console.log(this.userInfo); } } } </script>