使用计算属性可以避免重复计算。计算属性和methods中方法的区别就是:计算属性中方法返回的值会基于其响应式依赖被缓存,而普通方法会每次重新执行不缓存。
export default {
data() {
return {
author: {
name: 'John Doe',
books: [
'Vue 2 - Advanced Guide',
'Vue 3 - Basic Guide',
'Vue 4 - The Mystery'
]
}
}
},
computed: {
// 一个计算属性的 getter
publishedBooksMessage() {
// `this` 指向当前组件实例
return this.author.books.length > 0 ? 'Yes' : 'No'
}
}
}
<div :class="{ active: isActive }"></div>
<!-- 绑定多个class,就需绑定数组 -->
<div :class="[activeClass, errorClass]"></div>
// 对应的data()
data() {
return {
activeClass: 'active',
errorClass: 'text-danger'
}
}
<MyComponent :class="{ active: isActive }" />
<h1 v-if="awesome">Vue is awesome!h1>
<div v-if="type === 'A'">
A
div>
<div v-else-if="type === 'B'">
B
div>
<div v-else-if="type === 'C'">
C
div>
<div v-else>
Not A/B/C
div>
<template v-if="ok">
<h1>Titleh1>
<p>Paragraph 1p>
<p>Paragraph 2p>
template>
<inuput @click="a++" />
<input v-model:udata="user.data" />
Vue2 | Vue3 |
---|---|
beforeCreate | Not needed* |
created | Not needed* |
beforeMount | onBeforeMount |
mounted | onMounted |
beforeUpdate | onBeforeUpdate |
updated | onUpdated |
beforeDestroy | onBeforeUnmount |
destroyed | onUnmounted |
vue的生命周期
this.$refs.input
例如:
<script>
export default {
mounted() {
this.$refs.input.focus()
}
}
</script>
<template>
<input ref="input" />
</template>
vue3中由于没有this所以不能用this.$refs.elem的形式获取,而是通过setup的形式来获取
可以用组合式API或选项式API
<template>
<div ref="box"></div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
const box = ref(null)
// 须在mounted后才可输出引用的DOM元素
onMounted(() => {
console.log(box.value)
})
</script>
<script>
import MyComponent from './App.vue'
app.component('MyComponent', MyComponent)
</script>
<script>
import ButtonCounter from './ButtonCounter.vue'
export default {
components: {
ButtonCounter
}
}
</script>
<template>
<h1>Here is a child component!</h1>
<ButtonCounter />
<ButtonCounter />
</template>
</script>
每个被使用的组件会创建新实例,所以有各自独立的状态
export default {
props: ['foo'],
created() {
// props 会暴露到 `this` 上
console.log(this.foo)
}
}
export default {
props: {
title: String,
likes: Number
}
}
<BlogPost title="My journey with Vue" />
<BlogPost :title="post.title" />
<BlogPost :title="post.title + ' by ' + post.author.name" />
<button @click="$emit('someEvent')">click mebutton>
export default {
methods: {
submit() {
this.$emit('someEvent')
}
}
}
v-model 可以在组件上使用以实现双向绑定。
例如:
<input v-model="searchText" />
与下等价:
<input
:value="searchText"
@input="searchText = $event.target.value"
/>
而当使用在一个组件上时,v-model 会被展开为如下的形式:
<CustomInput
:modelValue="searchText"
@update:modelValue="newValue => searchText = newValue"
/>
将组件使用处的内容,放于其模板中的占位,进而渲染
<FancyButton> Click me! FancyButton>
<button class="fancy-btn">
<slot>slot>
button>