<template> <div>{{ message }}</div> </template> <script> export default { data() { return { message: 'Hello, Vue!' } } } </script> <style> div { color: blue; } </style>二. Vue 实例是什么?
Vue 实例是 Vue 应用的根实例,通过实例我们可以访问所有的 Vue 功能和生命周期钩子。
const app = new Vue({ el: '#app', data: { message: 'Hello, Vue!' } });在这个例子中,我们创建了一个新的 Vue 实例,并将其挂载到 #app 元素上。我们可以通过 data 选项定义数据,并在模板中使用这些数据。
export default { data() { return { message: 'Hello, Vue!' } }, created() { console.log('实例已创建'); }, mounted() { console.log('实例已挂载'); } }四. Vue 中的计算属性和侦听器有什么区别?
export default { data() { return { firstName: 'John', lastName: 'Doe' } }, computed: { fullName() { return this.firstName + ' ' + this.lastName; } } }侦听器:侦听器用于观察和响应数据的变化。它们更适合处理异步或较复杂的逻辑。
export default { data() { return { question: '' } }, watch: { question(newQuestion, oldQuestion) { this.getAnswer(newQuestion); } }, methods: { getAnswer(question) { // 异步操作 } } }五. Vue 中的指令是什么?
<div v-if="seen">现在你看到我了</div> <input v-model="message"> <ul> <li v-for="item in items" :key="item.id">{{ item.text }}</li> </ul> <button v-on:click="doSomething">点击我</button>六. Vue Router 是什么?
import Vue from 'vue'; import VueRouter from 'vue-router'; import Home from './components/Home.vue'; import About from './components/About.vue'; Vue.use(VueRouter); const routes = [ { path: '/', component: Home }, { path: '/about', component: About } ]; const router = new VueRouter({ routes }); new Vue({ router, render: h => h(App) }).$mount('#app');七. Vuex 是什么?
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++; } } }); new Vue({ store, render: h => h(App) }).$mount('#app');八. 如何处理 Vue 中的父子组件通信?
Vue.component('child', { props: ['message'], template: '<span>{{ message }}</span>' }); new Vue({ el: '#app', data: { parentMessage: 'Hello, World!' } }); <child :message="parentMessage"></child>子组件发送事件到父组件:通过 $emit。
Vue.component('child', { template: '<button @click="sendEvent">点击我</button>', methods: { sendEvent() { this.$emit('customEvent', 'Hello from Child'); } } }); new Vue({ el: '#app', data: { message: '' }, methods: { handleEvent(msg) { this.message = msg; } } }); <child @customEvent="handleEvent"></child> <p>{{ message }}</p>九. 什么是 Vue 的混入 (Mixin)?
const myMixin = { created() { this.hello(); }, methods: { hello() { console.log('Hello from mixin!'); } } }; new Vue({ mixins: [myMixin], created() { console.log('Hello from component!'); } });在这个例子中,混入和组件的 created 钩子都会被调用,输出两个不同的消息。这种方式可以让我们更好地复用代码。🚀
const Home = () => import('./components/Home.vue');**使用 v-once**:对于不需要更新的静态内容,使用 v-once 指令可以跳过重新渲染。
<p v-once>这个内容只渲染一次</p>避免不必要的计算属性:尽量减少计算属性的复杂度,确保它们是基于最少的依赖进行计算的。
<keep-alive> <component :is="view"></component> </keep-alive>总结