Vue 双向数据绑定、事件介绍 、以及ref获取dom节点
Vue 双向数据绑定(model、view)
template模板:
<template>
<div id="app">
<input type="text" v-model="msg">
</div>
</template>
js代码模块:
<script>
/*
* 双向数据绑定 MVVM vue本身就是一个MVVM的框架
* M model V view
* MVVM,model改变会影响视图view,view视图的改变会反过来作用影响model
*
* 双向数据绑定必须在表单中使用*/
export default {
name: 'app',
data() { /*业务逻辑里面定义的数据*/
return {
msg: '你好,Vue!'
}
},
}
</script>
运行结果:
Vue 事件介绍(v-on:click 或 @click)
template模块:
<template>
<div id="app">
<input type="text" v-model="msg">
<button v-on:click="getMsg()">获取表单里面的数据</button>
<button v-on:click="setMsg()">设置表单里面的数据</button>
</div>
</template>
js模块:
<script>
/*
* 双向数据绑定 MVVM vue本身就是一个MVVM的框架
* M model V view
* MVVM,model改变会影响视图view,view视图的改变会反过来作用影响model
*
* 双向数据绑定必须在表单中使用*/
export default {
name: 'app',
data() { /*业务逻辑里面定义的数据*/
return {
msg: '你好,Vue!'
}
},
methods: { /*放方法的地方*/
getMsg() {
//在方法里面获取data里面的数据
alert(this.msg);
},
setMsg() {
this.msg = "我是改变后的表单数据!"
},
}
}
</script>
运行结果:
Vue ref-获取dom节点
ref获得dom节点: ref=“username” ==>显示数据this.$refs.username.value
实例一
template:
<template>
<div id="app">
<input type="text" ref="userinfo"/>
<button v-on:click="getInputValue()">获取第二个表单里面的数据</button>
</div>
</template>
js:
<script>
export default {
name: 'app',
methods: { /*放方法的地方*/
getInputValue() {
console.log(this.$refs.userinfo);
alert(this.$refs.userinfo.value);
},
}
}
</script>
运行效果:
实例二
template:
<template>
<div id="app">
<div ref="box">This is a box!</div><br>
<button v-on:click="changeBoxBackground()">改变box的背景颜色</button>
</div>
</template>
js:
changeBoxBackground() {
this.$refs.box.style.background = 'red';
}
运行效果:
完整代码如下:
template:
<template>
<div id="app">
<input type="text" v-model="msg">
<button v-on:click="getMsg()">获取表单里面的数据</button>
<button v-on:click="setMsg()">设置表单里面的数据</button>
<br><hr>
<input type="text" ref="userinfo"/>
<button v-on:click="getInputValue()">获取第二个表单里面的数据</button>
<br><hr>
<div ref="box">This is a box!</div><br>
<button v-on:click="changeBoxBackground()">改变box的背景颜色</button>
</div>
</template>
js:
<script>
/*
* 双向数据绑定 MVVM vue本身就是一个MVVM的框架
* M model V view
* MVVM,model改变会影响视图view,view视图的改变会反过来作用影响model
*
* 双向数据绑定必须在表单中使用*/
export default {
name: 'app',
data() { /*业务逻辑里面定义的数据*/
return {
msg: '你好,Vue!'
}
},
methods: { /*放方法的地方*/
getMsg() {
//在方法里面获取data里面的数据
alert(this.msg);
},
setMsg() {
this.msg = "我是改变后的表单数据!"
},
getInputValue() {
console.log(this.$refs.userinfo);
alert(this.$refs.userinfo.value);
},
changeBoxBackground() {
this.$refs.box.style.background = 'red';
}
}
}
</script>