Vue:实例演示,v-if,v-for,v-model,v-bind,v-on,计算属性和侦听器属性
一.实例演示,v-if,v-for,v-model,v-bind,v-on
方法 |
含义 |
v-bind |
自定义普通属性,快捷语法是一个”:”号 |
v-on |
事件属性,快捷语法是一个”@”符 |
v-model |
双向绑定 |
v-for |
v-for : (循环变量, 索引/键) in/of 数组/对象 :key |
v-if |
条件渲染流程判断,有单分支和多分支 |
①v-bind,自定义普通属性,快捷语法是一个”:”号
代码块
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"> <body>
<div class="box">
<!-- v-bind指令,自定义普通属性,-->
<p v-bind:style="style1">{{text}}</p>
<hr />
<!-- 快捷语法‘:’ -->
<p :style="style2">{{text}}</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
new Vue({
el: ".box",
data: {
text: "v-bind指令",
style1: "color:red",
style2: "background:blue",
},
});
</script>
</body
②v-on,事件属性,快捷语法是一个”@”符
代码块
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
new Vue({
el: ".box",
data: {
text: "v-on指令",
},
//事件方法
methods: {
click1() {
alert(this.text);
d;
},
},
});
</script>
③v-model,双向绑定
代码块
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
new Vue({
el: ".box",
data: { data1: "祖国未来可期" },
});
</script>
④v-for,列表渲染
代码块
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
new Vue({
el: ".box",
data: {
//渲染数组
item: ["苹果", "香蕉", "西瓜", "葡萄"],
//渲染对象
hobby: { hobby1: "羽毛球", hobby2: "篮球" },
//渲染对象数组
user: [
{ id: 1, name: "小张", get: "20" },
{ id: 2, name: "小红", get: "20" },
{ id: 3, name: "小朱", get: "20" },
],
},
});
</script>
⑤v-if,条件渲染
- 单分支
- 多分支
代码块
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
new Vue({
el: ".box",
data() {
return {
text: "点击显示或者隐藏",
flase: "true",
tips: "显示",
name: ["大众会员", "黄金会员", "铂金会员", "钻石会员", "非会员"],
point: 500,
text: "点击加积分",
};
},
});
</script>
二.计算属性和侦听器属性
方法 |
含义 |
键盘修饰符 |
todolist |
计算属性 |
conputed |
侦听器属性 |
watch |
①键盘修饰符:todolist
代码块
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
new Vue({
el: ".box",
data() {
return {
list: [],
};
},
methods: {
submit(ev) {
//原生判断键盘添加文字
// if (ev.key === "Enter") {
// this.list.unshift(ev.target.value);
// ev.target.value = null;
// }
//vue 键盘修饰符添加文字
this.list.unshift(ev.target.value);
ev.target.value = null;
console.log(ev.key);
},
},
});
</script>
②计算属性computed
代码块
<script>
new Vue({
el: ".box",
data() {
return {
//双向绑定sum
sum: "0",
//单价是50
money: 50,
};
},
//计算属性computed
computed: {
amount: {
//访问器属性get
get() {
//指当前sum变量*money变量
return this.sum * this.money;
},
},
},
});
</script>
③侦听器属性watch
代码块
<script>
new Vue({
el: ".box",
data() {
return {
//双向绑定sum
sum: "0",
//单价是50
money: 50,
res: 0,
max: 100,
};
},
//侦听器属性
watch: {
// 是用来监听某一个属性的值的变化,属性名要和data字段中的变量名相同
// 例如,我要监听"num"变量的变化
// sum(新的值,原来的值)
sum(newVal, oldVal) {
this.res = newVal * this.money;
//监听库存量
if (newVal > 20) {
this.max = newVal;
alert("库存不足");
}
},
},
});
</script>