vue中使用变量

拇指一代
  • 290
<template>
  <div>
    <ul>
      <li @click="num('a')"/>
      <li @click="num('b')"/>
      <li @click="num('b')"/>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      keys: '',
      a: [],
      b: [],
      c: []
    }
  },
  created() {

  },
  mounted() {
    console.log(this.keys)
  },
  methods: {
    num(type) {
      this.keys = type
    }
  }
}
</script>

现在问题是this.keys想代表this.a 或者this.b 如何处理?

回复
阅读 1.1k
2 个回答
linong
  • 26k

方案一:

<template>
  <div>
    <ul>
      <li @click="num(a)"/>
      <li @click="num(b)"/>
      <li @click="num(b)"/>
    </ul>
  </div>
</template>

<script> export default {
  data() {
    return {
      keys: [],
      a: [],
      b: [],
      c: []
    }
  },
  created() {

  },
  mounted() {
    console.log(this.keys)
  },
  methods: {
    num(type) {
      this.keys = type
      console.log(this.keys)
    }
  }
} </script>

方案二:

<template>
  <div>
    <ul>
      <li @click="num('a')"/>
      <li @click="num('b')"/>
      <li @click="num('b')"/>
    </ul>
  </div>
</template>

<script> export default {
  data() {
    return {
      keys: [],
      a: [],
      b: [],
      c: []
    }
  },
  created() {

  },
  mounted() {
    console.log(this.keys)
  },
  methods: {
    num(type) {
      this.keys = this[type]
      console.log(this.keys)
    }
  }
} </script>

computed一个keys变量可以呀,不用再data里面定义

computed: {
    keys() {
        return this.a; // 获取this.a
        // return this.b; // 获取this.b
        // return { a: this.a, b: this.b }; // 同时获取ab
    }
}
宣传栏