new Vue({
data: {
n: 0,
history: [],
inUndoMode: false
},
watch: {
n(newValue, oldValue) {
if (!this.inUndoMode) {
this.history.push({ from: oldValue, to: newValue });
}
}
},
template: `
<div>
{{n}}
<hr/>
<button @click="add1">+1</button>
<button @click="add2">+2</button>
<button @click="minus1">-1</button>
<button @click="minus2">-2</button>
<hr/>
<button @click="undo">撤销</button>
<hr/>
{{history}}
</div>
`,
methods: {
add1() {
this.n += 1;
},
add2() {
this.n += 2;
},
minus1() {
this.n -= 1;
},
minus2() {
this.n -= 2;
},
undo() {
const last = this.history.pop();
this.inUndoMode = true;
const old = last.from;
this.n = old;
this.$nextTick(() => {
this.inUndoMode = false; //让上面的先执行
});
}
}
}).$mount("#app");
\
import Vue from "vue/dist/vue.js";
// 讲计算属性的computed的
Vue.config.productionTip = false;
let id = 0;
const createUser = (name, gender) => {
id += 1;
return { id: id, name: name, gender: gender };
};
new Vue({
data() {
return {
users: [
createUser("张飞", "男"),
createUser("貂蝉", "女"),
createUser("吕布", "男"),
createUser("小乔", "女")
],
gender: ""
};
},
computed: {
displayUsers() {
const hash = {
male: "男",
female: "女"
};
const { users, gender } = this;
if (gender === "") {
return users;
} else if (typeof gender === "string") {
return users.filter((u) => u.gender === hash[gender]);
} else {
throw new Error("gender的值是意外的值");
}
}
},
methods: {
setGender(string) {
this.gender = string;
}
},
template: `
<div>
<div>
<button @click="setGender('')">全部</button>
<button @click="setGender('male')">男</button>
<button @click="setGender('famale')">女</button>
</div>
<ul>
<li v-for="(u,index) in displayUsers" :key="index">{{u.name}}---{{u.gender}}</li>
</ul>
</div>
`
}).$mount("#app");