终极 Vue.js(2021)备忘单
VueJS 备忘单,包括 VueRouter、Vuex 和 Composition API
如果你想要更多类似的内容,请点击关注并在 Twitter 上关注我@EricTheCoder_
我花了很多时间来创建这个备忘单,希望你会喜欢它!
如果您发现任何错误或有任何建议,请在本页底部发表评论。
必须有 VueJS 的 VSCode 扩展
- Vetur:语法高亮、格式化、Emmet、IntelliSense 等
- Vue VSCode 代码片段
VSCode 设置.json 的补充
emmet.includeLanguages: {
'vue' : 'html',
'vue-html': 'html'
}
如何安装 VueJS
Vue 是一个渐进式框架。您可以只在网页的一小部分中使用它,或者如果您愿意,也可以使用 Vue CLI 工具搭建完整的 VueJS 应用程序。
仅在网页的一部分上使用 Vue
- 添加包含指向 VueJS CDN 库的链接的“script”标签
- 添加另一个包含指向 Vue 应用程序文件 (app.js) 的链接的“script”标签
- 创建一个 id =“app”的 div,它将作为呈现 Vue 应用程序的容器。
以下是使用 Vue.js (index.html)的页面示例
<html>
<head>
<title>Ma page Vue.js</title>
</head>
<body>
<div id="app">
{{ title }}
</div>
<script src="https://unpkg.com/vue@next"></script>
<script src="./app.js"></script>
</boby>
</html>
(app.js)
// function to initialize Vue.js instance
Vue.createApp({
data() {
return {
title: "Hello Word Vue"
}
}
}).mount('#app')
// .mount specifies that the Vue application will be render in the div with id = "app"
创建一个完整的 VueJS 应用程序
创建 VueJS 项目的工具是 Vue CLI。你需要安装它
npm install -g @vue/cli
创建你的 VueJS 应用
vue create my-app-name
npm 运行服务
创建应用程序后,您可以将自己定位到文件夹中并启动开发服务器
cd my-app-name
npm run serve
Vue 添加
您可以使用“vue add”快捷方式将插件/库添加到您的 Vue 项目。以下是 3 个示例:
vue add vue-router
vue add vuex
vue add tailwind
入口点
Vue CLI 将创建多个文件夹和文件。起点是 public/index.html 和 "src/main.js"
import { createApp } from "vue";
import App from "./App.vue";
createApp(App).mount("#app");
因此,作为入口点的组件是 App.vue
使用 Vue 应用程序时,不会将任何 HTML 代码写入 index.html 文件。您的 HTML 代码将写入每个组件的 <template> 部分。
单文件组件
每个 Vue 组件都在其自己的 .vue 文件中定义,语法如下 <template> <script> <style>
<template>
<img alt="Vue logo" src="./assets/logo.png" />
<HelloWorld msg="Hello Vue 3" />
{{ message }}
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
components: {
HelloWorld
},
data() {
return {
message: 'Hello World'
}
},
}
</script>
<style scope >
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
text-align: center;
color: #2c3e50;
}
</style>
在当前组件内使用组件。
<template>
<HelloWorld msg="Hello Vue" />
</template>
然后需要导入组件文件:
import HelloWorld from './components/HelloWorld.vue'
组件道具
组件可以在渲染时定义并传递 props 值
props 是使用以下语法在组件内部定义的
props: {
title: {
type: String,
required: true,
default: 'Mon application'
}
},
Props 也可以与简写语法一起使用
props: ['title'],
然后,您可以在使用组件时为这些道具分配一个值
<div>
<nav-bar title="My App" />
</div>
组件文件位置
单文件组件保存在 src/components 或 src/pages 文件夹中,具体取决于组件是作为页面(例如 About.vue)还是可重用组件(例如 NavBar.vue)
组件数据()
data () 函数用于创建将在 Vue 应用程序中使用的响应式变量。每当响应式变量发生更改时,无论它是在页面中显示还是使用,Vue 都会立即更新它。
要在页面中显示反应变量或表达式,必须使用双括号 Vue 将用其值替换表达式的内容
// variable
{{ title }}
// expression
{{ title.toUpperCase() }}
VueJS 指令
VueJS 指令是可以插入到页面中的 HTML 属性,以修改 Vue 应用程序的渲染。
以下是可用指令的列表:
v-绑定
允许你为属性分配一个表达式。Vue 会将表达式替换为其值
(例如 image_url:“ http://www.example.com/car.jpg ”
<img v-bind:src="image_url" />
// ou syntaxe raccourci
<img :src="image_url" />
v-一次
使用 v-once 指令时,Vue 将仅插入一次表达式。因此,所有其他刷新操作都会忽略该表达式。
<div v-once>
{{ title }}
</div>
v-html
允许您使用 HTML 标签显示表达式。
例如:标题:“<h1>Hello World</h1>”
<div v-html="title">
</div>
v-模型
用于将输入元素的值与变量关联起来。如果更改其中一个值,Vue 将自动更新另一个值。因此,变量和输入元素的值将始终相同。
<input v-model="name" type="text" />
<div>
Nom : {{ name }}
</div>
v-if、v-else-if 和 v-else
根据表达式的真值或假值,使元素可见或不可见。当元素不可见时,元素不会在 HTML 中渲染。
<div v-if="amount > 100">
Free Shipping!
<div>
<div v-else-if="montant > 50">
Shipping: 9.95$
</div>
<div v-else>
Shipping: 19.95$
</div>
视频秀
根据表达式的真值或假值,使元素可见或不可见。元素在渲染过程中始终存在。不可见时,元素将使用 CSS 属性 display: none 进行渲染;
<div v-show="isError">
{{ errorMessage }}
</div>
v-for
显示项目列表
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
</ul>
注意,属性“key”是允许 Vue 唯一标识元素的必要属性
参考
允许您的 Vue 应用程序识别 html 元素并对该元素执行操作。
<input type="text" ref="name">
使用特殊对象 this.$refs 从 Vue 代码进行操作
methods: {
handleClick() {
console.log(this.$refs.name)
this.$refs.name.classList.add('active')
this.$refs.name.focus()
}
}
对“class”属性和“style”进行 v-bind
可以对 class 和 style 属性进行 v-bind
<div class="text-2xl" :class="isAdmin ? 'text-red-500' : 'text-gray-500'">
Hello World
</div>
注意 class 属性使用了两次。Vue 会在渲染时合并这两个属性。
也可以使用对象来发送“class”属性中的内容
<div :class="{ 'text-red-500': isAdmin, 'text-gray-500': !isAdmin }">
Hello World
</div>
注意对象的语法{属性:表达式},如果表达式返回 true,则该属性将被添加到类中
类似的语法适用于 style 属性
<div :style="{'margin-top': '10px', 'padding': '5px'">
Hello World
</div>
最后,类和样式属性可以通过在应用程序的其他位置创建的对象类型变量来定义
titleClass: {
'text-red-400': this.isAdmin,
'text-gray-500': !this.isAdmin
}
<div :class="titleClass">
Hello World
</div>
<template> 标签
此元素允许您使用 Vue 指令而无需创建 html 元素。
<template v-show="quantity === 0">
Quantity must be greater than zero
</template>
活动
Vue 允许您管理 JavaScript 事件,例如点击、输入、更改等。为此,您必须使用 v-on: 指令,后跟事件名称。
v-on:点击
允许您在单击元素时执行代码
<button v-on:click="name = 'Mike'">Display a message</button>
// or shortened syntax
<button @click="name = 'Mike'">Display a mssagee</button>
v-on:按键
允许您按下某个键(例如输入)来执行代码
<button v-on:keydown.enter="name = 'Mike'">Display a message</button>
// or shortened syntax
<button @click="name = 'Mike'">Display a message</button>
v-on 的其他可能值:keydown、keyup、keypress
.enter、tab、esc、up、down、left、right、delete 的其他可能值
v-on:提交
允许您在提交表单时运行代码
<form v-on:submit.prevent="name = 'Mike'">
<input v-model="name" type="text" />
<button type="submit">Save</button>
</form>
请注意,v-on:submit 指令后面有一个“.prevent”。此指令将阻止表单提交到服务器。
方法
Vue.js 允许你创建方法,以便在应用程序中放置可复用的代码块。创建方法的语法如下:
Vue.createApp({
data() {
return {
name: "Mike Taylor",
}
},
methods: {
resetName() {
this.name = ''
}
}
}).mount('#app')
注意 name 变量前面的关键字“this”。此关键字是必需的,用于在 Vue 实例中引用变量。
要调用一个方法,您只需使用其名称即可。
<input v-model="name" type="text" />
<button @click="resetName" type="text">Delete</button>
方法也可以包含参数
methods: {
resetName(newName) {
this.name = newName
}
}
<input v-model="name" type="text" />
<button @click="resetName('John')" type="text">Effacer</button>
方法也可以发送对象事件
methods: {
resetName(newName, e) {
this.name = newName
console.log(e.target.textContent)
}
}
<input v-model="name" type="text" />
<button @click="resetName('John', $event)" type="text">Delete</button>
注意特殊参数 $event 将对象事件发送给我们的方法
$emit
关键字 $emit 用于发出事件。然后,您的应用程序可以使用 v-on: event-name 捕获此事件。
methods: {
sendDelete() {
const userId = 10
this.$emit('delete', userId)
}
}
<div>
<nav-bar title="My App" v-on:delete="deleteUser" />
</div>
计算方法
与每次呈现应用程序时都会重新执行的其他方法不同,“计算”方法仅在其包含的变量被修改时才会重新执行。
computed: {
recalcTotal(items, taxes) {
return this.calcTotal(items, taxes)
}
}
然后就可以在我们的页面中调用“计算”方法。
<button @click="recalcTotal">Re-Calc</button>
请注意,没有使用参数或括号
观看方法
这些方法将“监视”一个变量,一旦它发生变化就会执行该方法的代码。
watch: {
title(newTitle, oldTitle) {
console.log(`Le titre ${oldTitle} à changé pour ${newTitle}`)
}
}
生命周期钩子方法
每个视图实例在创建时都会经历一系列初始化步骤——例如,它需要设置数据观察、编译模板、将实例挂载到 DOM 上,并在数据发生变化时更新 DOM。
在此过程中,它还将调用生命周期钩子,这使我们有机会在每个步骤中执行自定义逻辑。
例如,在实例创建后调用“created”钩子
created() {
console.log('Component instance created')
}
还有其他几种钩子方法。以下列举一些:
beforeCreate
创建
beforeMount
安装
beforeUpdate
更新
beforeDestroy
销毁
老虎机
插槽允许您向组件添加内容
<custom-button>
...custom content...
Titre: {{ title }}
</custom-button>
请注意,“title”的渲染将在父组件中完成。同样的原则也适用于 CSS。因此,插槽的内容必须在父组件中定义/可访问。
自定义按钮的内部看起来像这样:
<template>
<slot></slot>
</template>
slot 标签将被“custom-button”的内容替换
可以为插槽定义一个默认值
<template>
<slot>If nothing than display this</slot>
</template>
注意,默认值是在子组件中定义的,所以必须使用子组件中定义的变量或css。
多个插槽
允许您添加仅与特定插槽相关的内容
<custom-button>
Custom Content
<template #title>
{{ title }}
</template>
</custom-button>
#title 标识标题槽中的模板。也可以使用 v-slot: title 语法
自定义按钮的内部看起来像这样:
<template>
<slot></slot>
<slot name="title"></slot>
</template>
请注意,主插槽仍然可用
(这里的标签是可选的)但可以添加第二个带有名称的插槽
老虎机道具
老虎机可以有道具
<template>
<slot name="title" status="info"></slot>
</template>
然后可以使用道具
<custom-button>
custom content...
<template #title="titleProps">
{{ title }}
{{ titleProps.status }}
</template>
</custom-button>
可以使用“#default”为主插槽定义 Props
<template>
<slot type="ajout"></slot>
<slot name="title" status="info"></slot>
</template>
<custom-button>
<template #default="defaultProps">
custom content...
{{ defaultProps.type }}
</template>
<template #title="titleProps">
{{ title }}
{{ titleProps.status }}
</template>
</custom-button>
请注意,如果没有命名插槽,可以使用以下语法来使用默认的 Props
<custom-button #default="defaultProps">
custom content...
{{ defaultProps.type }}
</custom-button>
Vue 路由器
客户端路由
客户端路由允许您更改浏览器的 URL 地址并加载另一个 Vue 页面/组件,而无需刷新浏览器。这一切都归功于 VueRouter 库。
安装 VueRouer v4
npm install vue-router@4
// or vue cli plugin
vue add router
VueRouter 配置
在main.js中添加
import { createApp } from 'vue'
import App from './App.vue'
import * as VueRouter from 'vue-router'
import Home from './pages/Home.vue'
import About from './pages/About.vue'
const router = VueRouter.createRouter({
history: VueRouter.createWebHistory(),
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: About
}
]
})
const app = createApp(App)
app.use(router).mount('#app')
app.mount('app')
路由器视图
该组件来自 vue-router 库,并作为容器来呈现我们定义的路由
App.vue
<router-view></router-view>
RouterLink
点击此元素时,Vue 将渲染由 router-link 标签和 to = 属性指定的路由。渲染将在你放置 <router-view> </router-view> 的位置进行。
<template>
<div>
<h1>Home page</h1>
<router-link to="/about">About</router-link>
// or
<router-link :to="{ name: About }">About</router-link>
</div>
</template>
<script>
export default {
}
</script>
<style lang="scss" scoped>
</style>
路由参数
可以提取与路径相关的信息。例如产品的 ID:/products/id
routes: [
...
...
{
path: '/products/:id',
name: 'ProductDetails',
component: ProductDetails
},
]
})
然后您可以从产品组件启动链接
<router-link :to="{ name: 'ProductDetails', params: { id: product.id }}">
See details
</router-link>
最终可以从 ProductDetail 组件读取此参数:
<template>
The product ID is {{ $route.params.id }}
</template>
也可以将此参数读取为组件Props(例如ProductDetails组件)
<template>
The product ID is {{ idid }}
</template>
<script>
export default {
props: ['id'],
}
</script>
为了能够将参数转换为 Props,您必须在定义路由时提及它。
routes: [
...
...
{
path: '/products/:id',
name: 'ProductDetails',
component: ProductDetails,
props: true,
},
]
})
$route / this.$route
是一个包含当前路线信息的全局对象:
- 姓名
- 完整路径
- 小路
- 询问
- 参数
路由重定向
可以从一条道路改道到另一条道路。
routes: [
...
...
{
path: '/about-us',
redirect: '/about',
},
]
})
路由别名
可以有两条路线显示相同的组件
routes: [
{
path: '/',
name: 'Home',
component: Home,
alias: '/home'
},
]
})
'/' 和 '/home' 指向同一个组件。
alias 属性也可以是数组['/home', '/homepage']
404 重定向
如果路由不存在,则可以重定向页面
routes: [
...
...
{
path: '/:catchAll(.*)',
name: 'NotFound',
component: NotFount
},
]
})
使用 this.$router 修改代码中的路由
methods: {
redirect() {
this.$router.push({ name: 'Home' })
},
back() {
this.$router.go(-1)
// or same thing
this.$router.back()
},
forward() {
this.$router.go(1)
// or same thing
this.$router.forward()
}
}
路线查询
可以读取传递给路由的查询参数
,例如:/products?brand=Apple
<template>
Filter Brand : {{ $route.query.brand }}
</template>
可以使用查询参数调用路由
methods: {
search(brand) {
this.$router.push({ name: 'Home', query: brand })
},
}
如果查询等于*未定义*,则它不会出现在浏览器的 URL 栏中
嵌套路由
允许您管理子路线。例如:/products/1050/tags
您必须首先使用属性 * children * 定义子路由
routes: [
...
...
{
path: '/products/:id',
name: 'ProductDetails',
component: ProductDetails,
props: true,
children: {
path: 'tags',
components: Tags,
},
},
]
})
在 ProductDetails 组件中,您可以使用 <route-view> 标签显示组件标签
<template>
Product no
{{ $route.params.id }}
List of tags associated with the product
<router-view></router-view>
</template>
组合 API
是 Option API 的替代品,它允许我们以捆绑的方式更自然地编写代码,而无需使用属性/对象,也无需使用关键字“this”。
setup() 方法
组件的所有代码都将写入此方法中
<template>
</template>
<script>
export default {
setup() {
..component code..
}
}
</script>
<style>
</style>
请注意,模板和样式部分保持不变
setup()方法的返回值
如果要在setup()方法之外使用变量或函数,例如在模板中,则必须在return()方法中返回它
<template>
{{ title }}
</template>
<script>
export default {
setup() {
let title = 'My Title'
return {
title,
}
}
}
</script>
道具
您可以使用 props 参数访问组件的 props
<script>
export default {
props: ['title']
setup(props) {
console.log(props.title)
return {
}
}
}
</script>
反应变量
要在变量上使用 v-model 指令,必须使用函数 ref() 使该变量具有反应性
<template>
<input v-model="title">
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
let title = ref('My Title')
return {
title,
}
}
}
</script>
.value 属性
要修改用 ref() 声明的反应变量,必须使用其 .value 属性
<template>
<input v-model="title">
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
let title = ref('My Title')
title.value = 'Hello World'
return {
title,
}
}
}
</script>
ref 指令链接 HTML 元素
ref 指令也可用于创建与 html 元素的绑定(替换 API 选项中的 this.$ref)
<input :ref="title" type="text" />
<script>
import { ref } from 'vue'
export default {
setup() {
import { ref } from 'vue'
const title = ref(null)
return {
title,
}
}
</script>
Reactive:ref 函数的替代方案
<template>
<input v-model="state.title">
</template>
<script>
import { reactive } from 'vue'
export default {
setup() {
const state = reactive({
title: 'My Title'
}
state.title = 'Hello World'
return {
person,
}
}
}
</script>
请注意,反应函数仅将对象作为值(没有字符串、数字等),并且与 ref() 函数不同,您不应使用 .value 属性来返回变量的值。
BeforeCreate 和 Created 生命周期钩子的组合
要在创建组件时运行代码,只需将一些代码直接放在 setup() 中
<template>
<input v-model="title">
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
let title = ref('My Title')
title.value = 'Default value on creation'
return {
title,
}
}
}
</script>
已安装
允许您在创建组件时运行代码
<script>
export default {
import { onMounted, ref } from 'vue'
setup() {
let products = ref(null)
onMounted(async () => {
const response = await fetch('https://fakestoreapi.com/products')
products.value = await response.json()
})
}
</script>
发射
emit 函数替换 $emit
<template>
<button @click="save">save</button>
</template>
<script>
import { ref } from 'vue'
export default {
setup(props, { emit } ) {
const id = 12
const save = function() {
emit('onCLickEvent', id)
}
return {
save,
}
}
}
</script>
使用 Store(Vuex)
this.$store 方法在组合 API 模式下不可用,现在必须使用 useStore() 方法
<template>
<input v-model="title">
<button @click="saveTitle">save</button>
</template>
<script>
import { ref } from 'vue'
import { useStore ] from 'vuex'
export default {
setup() {
let title = ref('My Title')
const store = useStore()
title.value = store.state.title
return {
title,
saveTitle: () => store.commit('save')
}
}
}
</script>
注意,saveTitle 函数实际上是一个函数。返回一个函数允许你不立即执行提交,而是在调用 saveTitle 时执行。
computed() 方法
<script>
import { ref, computed } from 'vue'
import { useStore ] from 'vuex'
export default {
setup() {
let title = ref('My Title')
const store = useStore()
title.value = store.state.title
return {
title,
count: computed(() => store.state.count)
}
}
}
</script>
仅当“state.count”的值发生变化时,计算变量“count”才会刷新。
观看方法
允许您在修改变量时运行代码
<script>
import { ref, watch } from 'vue'
import { useStore ] from 'vuex'
export default {
setup() {
let title = ref('My Title')
const store = useStore()
watch(title, (new, old) => {
console.log('The title have change')
}
return {
title,
count: computed(() => store.state.count)
}
}
}
</script>
要同时监视多个变量,可以使用函数 watchEffect ()
watchEffect(() => {
console.log(count, title)
}
该函数将在 watchEffect() 中存在的所有变量的每次修改时运行
使用路由器和路由
在 Composition API 模式下,您不能使用 'this.$router' 和 'this.$route',您必须使用 useRouter 和 useRoute
<script>
import { useRouter, useRoute) from 'vue-router'
export default {
setup() {
const router = useRouter()
const route = useRoute()
router.push({ name: 'Home' })
console.log(route.path, route.params)
}
}
</script>
<脚本设置>
可以使用缩写语法来创建 API 组合的代码
<script setup>
import { ref, watch } from 'vue'
import { useStore ] from 'vuex'
let title = ref('My Title')
const store = useStore()
watch(title, (new, old) => {
console.log('The title have change')
}
</script>
请注意,“script setup”属性允许不使用setup()方法,也不返回任何值。它们会被自动管理。Vue会返回在顶层定义的所有变量和函数。
使用 setup 属性进行 props 和 emit
<script setup">
import{ defineProps, defineEmit, useContext } from 'vue'
defineProps(['msg']);
// or
defineProps({
title: String,
})
// or
const props = defineProps({
title: String,
})
// console.log(props.title)
const emit = defineEmit(['handleClick'])
const { slot, attrs } = useContext()
</script>
样式 v-bind
使用 Vue 3.2,现在可以在样式部分中使用 v-bind
<script setup>
import { ref } from 'vue'
let color = ref('red')
</script>
<style scope>
css
.title {
颜色:v-bind(颜色);
}
### Conclusion
Thank you for reading this article. If you want more content like this, click <strong> Follow <string> or <a href="https://twitter.com/EricTheCoder_" class="twitter-follow-button"> follow me on Twitter </a>