方法属性
@click是一个语法糖,它的另一种写法是v-on:click,通过这种方式调用方法
而方法一般放入methods属性中
<template>
<button @click="msg">点击测试</button>
</template>
<script>
export default {
methods:{
msg(){
console.log("Hello World!");
}
}
}
</script>
for循环
<template>
<ul>
<li v-for="(person,index) of personList" :key="person.id">
{{ index+1 }}. 人员编号:{{ person.id }},姓名:{{ person.name }}
</li>
</ul>
</template>
<script>
export default {
data(){
return{
personList:[
{id:10,name:'a',age:11},
{id:20,name:'b',age:12},
{id:30,name:'c',age:13}
],
}
},
methods:{
}
}
</script>
if语句
<template>
<ul>
<li v-for="(person,index) of personList" :key="person.id">
{{ index+1 }}. 人员编号:{{ person.id }},姓名:{{ person.name}}
<p v-if="person.age>=18">成年</p>
<p v-else-if="person.age<18 && person.age>=0">未成年</p>
<p v-else>年龄不能小于0</p>
</li>
</ul>
</template>
<script>
export default {
data(){
return{
personList:[
{id:10,name:'a',age:21},
{id:20,name:'b',age:12},
{id:30,name:'c',age:-2}
],
}
},
methods:{
}
}
</script>
<style>
</style>
计算属性computed
与方法属性不同的是,它带有缓存,如果再次调用这个方法前,数据还是不变,就不调用了。
<template>
<ul>
<li v-for="(person,index) of personList" :key="person.id">
{{ index+1 }}. 人员编号:{{ person.id }},姓名:{{ person.name}}
<p v-if="person.age>=18">成年</p>
<p v-else-if="person.age<18 && person.age>=0">未成年</p>
<p v-else>年龄不能小于0</p>
</li>
</ul>
<p>{{ sumAge }}</p>
</template>
<script>
export default {
data(){
return{
sumAge:0,
personList:[
{id:10,name:'a',age:21},
{id:20,name:'b',age:12},
{id:30,name:'c',age:-2}
],
}
},
computed:{
sumAge(){
let sum=0;
this.personList.forEach((person)=>{
sum+=person.age;
})
return sum;
}
},
methods:{
}
}
</script>
<style>
</style>
侦听器watch
<template>
<span>输入一些东西</span>
<input v-model="question" />
</template>
<script>
export default {
data(){
return{
question:""
}
},
watch:{
question(newQuestion,oldQuestion)
{
if(newQuestion.includes('?'))
{
console.log("有问号")
}else{
console.log("没有")
}
}
}
}
</script>
函数不写括号小细节
不写括号时,会默认传入一个event对象,还没深入学习这个东西,但是记住有大用就行。
以下代码是当点击按钮时,通过ref找到span,将里面的内容更改.
<template>
<span ref="mySpan">哈哈哈</span>
<button @click="a">测试</button>
</template>
<script>
export default {
methods:{
a(e){
this.$refs.mySpan.innerHTML="HELLO WORLD!"
}
}
}
</script>
<style>
</style>