study blog1

文章介绍了如何使用Vue.js实现一个简单的计数器和用户列表,其中包含undo/redo功能以及使用计算属性进行动态过滤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值