Skip to content

Vue 实例与模板语法

Vue 实例是Vue应用的核心,而模板语法是Vue中用于构建用户界面的重要部分。本章节将介绍Vue实例的创建和Vue的模板语法。

Vue 实例

1. 创建 Vue 实例

在Vue3中,我们使用 createApp 函数来创建Vue应用实例:

javascript
import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)
app.mount('#app')
  • createApp:创建一个新的Vue应用实例
  • App:根组件
  • mount:将应用实例挂载到DOM元素上

2. 应用实例的配置

你可以在创建应用实例后,对其进行配置:

javascript
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import { createPinia } from 'pinia'

const app = createApp(App)

// 注册插件
app.use(router)
app.use(createPinia())

// 全局属性
app.config.globalProperties.$message = 'Hello Vue3!'

// 错误处理
app.config.errorHandler = (err, instance, info) => {
  console.error('Error:', err)
  console.log('Instance:', instance)
  console.log('Info:', info)
}

app.mount('#app')

模板语法

Vue的模板语法是一种基于HTML的声明式语法,它允许你将Vue的响应式数据绑定到DOM上。

1. 插值表达式

语法

作用:将数据绑定到模板中

示例

vue
<template>
  <div>
    <h1>{{ message }}</h1>
    <p>{{ count * 2 }}</p>
    <p>{{ user.name }}</p>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'

const message = ref('Hello Vue3!')
const count = ref(0)
const user = reactive({ name: 'John' })
</script>

2. 指令

指令是带有 v- 前缀的特殊属性,用于在模板中执行各种操作。

v-bind

作用:绑定HTML属性 简写:

vue
<template>
  <div>
    <img :src="imageUrl" :alt="imageAlt">
    <div :class="{ active: isActive }">Active</div>
    <div :style="{ color: textColor, fontSize: '16px' }">Styled text</div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'

const imageUrl = ref('https://example.com/image.jpg')
const imageAlt = ref('Example image')
const isActive = ref(true)
const textColor = ref('red')
</script>

v-model

作用:双向绑定 示例

vue
<template>
  <div>
    <input v-model="message" type="text">
    <p>{{ message }}</p>
    <input v-model="count" type="number">
    <p>{{ count }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const message = ref('')
const count = ref(0)
</script>

v-on

作用:绑定事件 简写@

vue
<template>
  <div>
    <button @click="increment">Increment</button>
    <p>{{ count }}</p>
    <button @click="sayHello('Vue3')">Say Hello</button>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const count = ref(0)

const increment = () => {
  count.value++
}

const sayHello = (name) => {
  alert(`Hello ${name}!`)
}
</script>

v-if / v-else / v-else-if

作用:条件渲染 示例

vue
<template>
  <div>
    <div v-if="score >= 90">优秀</div>
    <div v-else-if="score >= 80">良好</div>
    <div v-else-if="score >= 60">及格</div>
    <div v-else>不及格</div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const score = ref(85)
</script>

v-show

作用:显示/隐藏元素 示例

vue
<template>
  <div>
    <button @click="toggle">Toggle</button>
    <div v-show="isVisible">This is visible</div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const isVisible = ref(true)

const toggle = () => {
  isVisible.value = !isVisible.value
}
</script>

v-for

作用:列表渲染 示例

vue
<template>
  <div>
    <ul>
      <li v-for="(item, index) in items" :key="index">
        {{ item.name }} - {{ item.age }}
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const items = ref([
  { name: 'John', age: 25 },
  { name: 'Jane', age: 30 },
  { name: 'Bob', age: 35 }
])
</script>

3. 模板表达式

在Vue模板中,你可以使用JavaScript表达式:

vue
<template>
  <div>
    <p>{{ count + 1 }}</p>
    <p>{{ message.toUpperCase() }}</p>
    <p>{{ isActive ? 'Active' : 'Inactive' }}</p>
    <p>{{ items.filter(item => item.age > 25) }}</p>
  </div>
</template>

4. 模板指令修饰符

指令修饰符是以点开头的特殊后缀,用于修改指令的行为:

v-on 修饰符

vue
<template>
  <div>
    <form @submit.prevent="onSubmit">
      <button type="submit">Submit</button>
    </form>
    <button @click.stop="onClick">Stop propagation</button>
    <button @click.once="onClickOnce">Click once</button>
  </div>
</template>

<script setup>
const onSubmit = () => {
  console.log('Form submitted')
}

const onClick = () => {
  console.log('Button clicked')
}

const onClickOnce = () => {
  console.log('Button clicked once')
}
</script>

v-model 修饰符

vue
<template>
  <div>
    <input v-model.lazy="message" type="text">
    <input v-model.number="count" type="number">
    <input v-model.trim="name" type="text">
  </div>
</template>

<script setup>
import { ref } from 'vue'

const message = ref('')
const count = ref(0)
const name = ref('')
</script>

模板编译

Vue的模板会被编译成渲染函数,然后执行渲染函数生成虚拟DOM,最后将虚拟DOM渲染成真实DOM。

编译过程

  1. 模板解析:将模板解析成抽象语法树(AST)
  2. 优化:标记静态节点,避免不必要的更新
  3. 代码生成:将AST编译成渲染函数

渲染函数

如果你熟悉JavaScript,也可以直接使用渲染函数来构建UI:

javascript
import { h } from 'vue'

export default {
  render() {
    return h('div', {
      class: { active: this.isActive }
    }, [
      h('h1', this.title),
      h('p', this.message)
    ])
  },
  data() {
    return {
      isActive: true,
      title: 'Hello Vue3!',
      message: 'This is a render function example'
    }
  }
}

总结

Vue的实例和模板语法是Vue应用的基础。通过Vue实例,你可以创建和配置Vue应用;通过模板语法,你可以构建响应式的用户界面。

在后续的章节中,我们将深入学习Vue3的核心基础语法,包括数据绑定、指令、计算属性等内容。

© 2026 编程马·菜鸟教程 版权所有