Vue3语法

-
-
2025-09-26 12:31

通过CDN可快速引入Vue3:

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

1. v-if

格式:

<h1 v-if="condition">条件为真</h1>
<h1 v-else>条件为假</h1>

只有condition时渲染这个标签,条件为假则会被从DOM中移除。

代码示例:

<script>
export default {
  data() {
    return {
      awesome: true
    }
  },
  methods: {
    toggle() {
      // ...
      this.awesome = !this.awesome;
    }
  }
}
</script>

<template>
  <button @click="toggle">Toggle</button>
  <h1 v-if="awesome">Vue is awesome!</h1>
  <h1 v-else>Oh no 😢</h1>
</template>

2. 计算属性

格式:

computed: {
	method_name() {
		return this.attr;
	}
}

<span>{{ method_name }}</span>

通过计算属性的方式,会得到一个缓存,即:无论调用多少次method_name, 只要它的响应式依赖没变,所得的结果就会都是一样的。

 

 


目录