Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:
作业内容:实例演示条件渲染, 计算属性和侦听器,并比较计算属性与侦听器之间的区别,一定要实例演示才可以看到区别
<!-- 引入vue框架库 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- 条件渲染 v-if, v-show -->
<div class="app1">
<!-- 条件渲染 v-if -->
<!-- 满足条件时,才会添加到 dom 中 -->
<p><input type="number" v-model="num" @change="changenum($event)" /></p>
<p v-if="num >= 0 && num <= 10">num >= 0 && num <= 10</p>
<p v-else-if="num > 10 && num <= 20">num > 10 && num <= 20</p>
<p v-else>num < 0 || num> 20</p>
<!-- 条件渲染 v-show -->
<!-- num <= 20 时,v-show 隐藏,但 dom 中存在 -->
<p v-show="num > 20">num > 20</p>
</div>
<script>
const vm1 = new Vue({
el: document.querySelector('.app1'),
data() {
return {
num: 0,
}
},
methods: {
changenum(ev) {
this.num = ev.target.value;
}
},
});
</script>
<!-- 计算属性和侦听器 -->
<div class="app2">
<p><input type="number" /> <button @click="clicknum($event)">sum</button></p>
<p>sum = {{sum}}</p>
<p v-for="(item, index) of watcharr" :key="index">{{index}} - {{item}}</p>
</div>
<script>
const vm2 = new Vue({
el: document.querySelector('.app2'),
data() {
return {
num: 0,
count: 0,
watcharr: [],
}
},
// 方法
methods: {
clicknum(ev) {
this.num = ev.target.previousElementSibling.value;
this.count ++;
},
},
// 计算属性
computed: {
sum() {
let sum = 0;
for (let i = 0; i <= this.num; i++) {
sum += i;
}
return sum;
},
},
// 侦听器属性
watch: {
num(newvalue, oldvalue) {
this.watcharr.push(`点击第 ${this.count} 次, 新值 ${newvalue}, 旧值 ${oldvalue}`);
}
}
});
</script>