当前位置:首页 > VUE

vue实现指引

2026-01-14 00:35:21VUE

Vue 实现指引

安装 Vue

使用 npm 或 yarn 安装 Vue 的最新版本:

npm install vue

yarn add vue

创建 Vue 实例

在 HTML 文件中引入 Vue,并创建一个 Vue 实例:

<div id="app">
  {{ message }}
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
  const { createApp } = Vue

  createApp({
    data() {
      return {
        message: 'Hello Vue!'
      }
    }
  }).mount('#app')
</script>

使用单文件组件

Vue 单文件组件(.vue)将模板、逻辑和样式封装在一个文件中:

<template>
  <div>
    <h1>{{ title }}</h1>
    <button @click="increment">Count: {{ count }}</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      title: 'Vue Component',
      count: 0
    }
  },
  methods: {
    increment() {
      this.count++
    }
  }
}
</script>

<style scoped>
h1 {
  color: #42b983;
}
</style>

使用 Vue CLI 或 Vite 搭建项目

Vue CLI 是官方提供的脚手架工具:

npm install -g @vue/cli
vue create my-project

Vite 是一个现代化的构建工具,支持 Vue:

npm create vite@latest my-vue-app --template vue

常用指令

Vue 提供了一系列指令用于绑定数据和操作 DOM:

  • v-bind:动态绑定属性
  • v-model:双向数据绑定
  • v-for:列表渲染
  • v-if / v-else:条件渲染
  • v-on:事件监听

示例:

<template>
  <div>
    <input v-model="inputText" placeholder="Type something">
    <p>{{ inputText }}</p>
    <ul>
      <li v-for="item in items" :key="item.id">{{ item.name }}</li>
    </ul>
    <button v-on:click="handleClick">Click me</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      inputText: '',
      items: [
        { id: 1, name: 'Item 1' },
        { id: 2, name: 'Item 2' }
      ]
    }
  },
  methods: {
    handleClick() {
      alert('Button clicked!')
    }
  }
}
</script>

状态管理(Vuex/Pinia)

对于大型应用,可以使用 Vuex 或 Pinia 管理全局状态:

vue实现指引

npm install pinia

示例(Pinia):

// stores/counter.js
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0
  }),
  actions: {
    increment() {
      this.count++
    }
  }
})

在组件中使用:

<template>
  <div>
    <p>{{ counter.count }}</p>
    <button @click="counter.increment">Increment</button>
  </div>
</template>

<script>
import { useCounterStore } from '@/stores/counter'

export default {
  setup() {
    const counter = useCounterStore()
    return { counter }
  }
}
</script>

路由(Vue Router)

使用 Vue Router 实现页面导航:

npm install vue-router

示例:

// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router

在 main.js 中引入:

vue实现指引

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

createApp(App).use(router).mount('#app')

组合式 API

Vue 3 引入了组合式 API,提供更灵活的代码组织方式:

<template>
  <div>
    <p>{{ count }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

<script>
import { ref } from 'vue'

export default {
  setup() {
    const count = ref(0)

    function increment() {
      count.value++
    }

    return {
      count,
      increment
    }
  }
}
</script>

生命周期钩子

Vue 组件提供了一系列生命周期钩子:

<script>
export default {
  created() {
    console.log('Component created')
  },
  mounted() {
    console.log('Component mounted')
  },
  updated() {
    console.log('Component updated')
  },
  unmounted() {
    console.log('Component unmounted')
  }
}
</script>

组合式 API 中的生命周期钩子:

<script>
import { onMounted, onUnmounted } from 'vue'

export default {
  setup() {
    onMounted(() => {
      console.log('Component mounted')
    })

    onUnmounted(() => {
      console.log('Component unmounted')
    })
  }
}
</script>

测试

使用 Vue Test Utils 进行组件测试:

npm install @vue/test-utils jest

示例测试:

import { mount } from '@vue/test-utils'
import Counter from '@/components/Counter.vue'

describe('Counter.vue', () => {
  it('increments count when button is clicked', async () => {
    const wrapper = mount(Counter)
    await wrapper.find('button').trigger('click')
    expect(wrapper.text()).toContain('1')
  })
})

部署

构建生产环境代码:

npm run build

部署生成的 dist 文件夹到静态服务器或 CDN。

标签: vue
分享给朋友:

相关文章

vue设计与实现下载

vue设计与实现下载

vue设计与实现电子书下载 《Vue.js设计与实现》是一本深入解析Vue.js框架原理的书籍,由霍春阳(HcySunYang)撰写。以下是获取该资源的常见途径: 正版购买渠道 京东、…

vue滚动实现

vue滚动实现

Vue 滚动实现方法 使用原生滚动 在 Vue 中可以通过 ref 获取 DOM 元素,调用原生滚动方法实现滚动效果。适用于简单场景。 <template> <div ref=…

vue实现curd

vue实现curd

Vue实现CRUD操作 初始化Vue项目 使用Vue CLI创建新项目,安装必要依赖如axios用于HTTP请求 vue create crud-demo cd crud-demo npm inst…

vue遮罩实现

vue遮罩实现

实现 Vue 遮罩的常见方法 使用 CSS 定位和透明度 创建一个全屏遮罩层,通过 CSS 固定定位覆盖整个视口,并设置半透明背景色。 <template> <div cl…

vue广播实现

vue广播实现

vue广播实现 在Vue中实现广播功能可以通过事件总线(Event Bus)或Vuex来完成。以下是两种常见的实现方式: 使用事件总线(Event Bus) 事件总线是一种简单的跨组件通信方式,适用…

使用vue实现搜索

使用vue实现搜索

使用 Vue 实现搜索功能 基础搜索实现 在 Vue 中实现搜索功能通常涉及数据绑定、事件监听和列表过滤。以下是一个简单的实现方式: <template> <div&g…