记录从后端转前端的第一天,回忆学过的 vue2.0
一.提前准备
从官网下载vue.js,网址:https://v2.cn.vuejs.org/
二.Vue基础一
MVVM 模型
M(model): data中数据的来源(后端传来的数据)
V(view):视图渲染(html代码)
VM(viewmodel): vue实例存放的data数据 (js代码)
vue语法
1.插值语法:{{}}
2.指令语法:v-bind,v-model…
数据绑定
单向数据绑定
-
语法:简写 :value=“xxx” (v-bind:value =“xxx” )
-
特点:数据流向:data --> view
双向数据绑定
-
语法:简写为v-model=“xxx” (v-mode:value=“xxx” )
-
特点:数据流向: data <–> view
代码示例
<body>
<div id="app">
姓名:<input type="text" :value="name">
年龄:<input type="text" v-model="age">
</div>
</body>
<script>
const vm=new Vue({
el:'#app',
data(){
return{
name:'1zx',
age:23
}
}
});
</script>
事件
事件
@click点击事件
事件修饰符
.prevent 阻止默认行为(阻止a标签页面跳转)
.stop 阻止冒泡行为
代码示例
<body>
<div id='app'>
<button @click="showInfo($event,100)">显示</button><br>
<a href="" @click.prevent="showInfo($event,100)">不允许跳转</a><br>
<div @click="showInfo($event,99)">
<a href="" @click.stop="showInfo($event,100)">不允许跳转</a>
</div>
</div>
</body>
<script>
const vm = new Vue({
el:'#app',
data(){
return{
name:'1zx',
age:'21',
}
},
methods:{
showInfo(event,num){
console.log(event),
alert(num)
}
}
})
</script>
计算属性和监视属性
计算属性—computed
根据data里的数据,计算一个新的属性值
代码示例
<body>
<div id="app">
<div>今天天气{{info}}~</div>
<button @click="changeWeather()">切换天气</button>
</div>
</body>
<script>
const vm = new Vue({
el:'#app',
data(){
return{
isHot:true
}
},
methods: {
changeWeather(){
this.isHot = !this.isHot
}
},
computed:{
info(){
return this.isHot?'热死人啦':'冷一点也是情有可原的'
}
}
})
</script>
监视属性—watch
深度检测
代码示例(监测坐标对象的x,y,z变化)
<body>
<div id="app">
<div> you: (12 ,13 ,25)</div>
<div>  me: ({{num.x}} ,{{num.y}} ,{{num.z}})</div>
<button @click="fx">改变x</button>
<button @click="fy">改变y</button>
<button @click="fz">改变z</button>
</div>
</body>
<script>
const vm = new Vue({
el:'#app',
data(){
return{
num:{
x:0,
y:0,
z:0
},
}
},
methods:{
fx(){
if(this.num.x=='12'){return}
this.num.x=Math.floor(Math.random()*26+1)
},
fy(){
if(this.num.y=='24'){return}
this.num.y=Math.floor(Math.random()*26+1)
},
fz(){
if(this.num.z=='26'){return}
this.num.z=Math.floor(Math.random()*26+1)
}
},
watch:{
num:{
immediate:true,//初始化就调用一次
deep:true,//深度监视
handler(){
if(this.num.x=='12'&&this.num.y=='24'&&this.num.z=='26'){alert('白首如新,倾盖如故')}
}
}
}
})
</script>
监视属性简写
watch:{
num(newValue,oldValue){
console.log(newValue);
}
}
建议
1.vue管理的函数不要写成箭头函数
2.非vue管理的函数建议写成箭头函数