当前位置: 首页 > news >正文

Vue3(一)

1.Vue3概述

Vue3的API由Vue2的选项式API改为了组合式API。但是,也是Vue2中的选项式API也是兼容的。

2.创建Vue3项目

create-vue 是 Vue 官方新的脚手架工具,底层切换到了 vite。使用create-vue创建项目的步骤如下:

安装 create-vue

npm init vue@latest

项目中关键文件的含义

3.组合式API

3.1.setup选项

setup 函数是在 beforeCreate 钩子之前执行。并且,在setup函数中写的数据和方法需要在末尾以对象的方式 return,才能给模版使用。

<script>export default {setup(){const message = 'this is message'const logMessage = ()=>{console.log(message)}// 必须return才可以return {message,logMessage}}}
</script>

也可以给 script 标签添加 setup 标记,这样 script 标签内部所有的代码相当于都是在 setup 函数内,导出语句也会被默认添加上。

<script setup>const message = 'this is message'const logMessage = ()=>{console.log(message)}
</script>

3.2.reactive和ref函数

reactive:用来接受对象类型数据的传入并返回一个响应式的对象。

<script setup>// 导入import { reactive } from 'vue'// 执行函数 传入参数 变量接收const state = reactive({msg:'this is msg'})const setSate = ()=>{// 修改数据更新视图state.msg = 'this is new msg'}
</script><template>{{ state.msg }}<button @click="setState">change msg</button>
</template>

ref:接收简单类型或者对象类型的数据传入并返回一个响应式的对象。基本用的都是这种。

<script setup>// 导入import { ref } from 'vue'// 执行函数 传入参数 变量接收const count = ref(0)const setCount = ()=>{// 修改数据更新视图必须加上.valuecount.value++}
</script><template><button @click="setCount">{{count}}</button>
</template>

3.3.computed

会基于现有的数据,计算出来的新属性。依赖的数据发生了变化,计算属性也会自动重新计算。

<script setup>
// 导入
import {ref, computed } from 'vue'
// 原始数据
const count = ref(0)
// 计算属性
const doubleCount = computed(()=>count.value * 2)// 原始数据
const list = ref([1,2,3,4,5,6,7,8])
// 计算属性list
const filterList = computed(() => {return list.value.filter(item => item > 2)
})
</script>

3.4.watch

侦听一个或者多个数据的变化,数据变化时执行回调函数,俩个额外参数 immediate控制立刻执行,deep开启深度侦听。

1.侦听单个数据

<script setup>// 1. 导入watchimport { ref, watch } from 'vue'const count = ref(0)// 2. 调用watch 侦听变化watch(count, (newValue, oldValue)=>{console.log(`count发生了变化,老值为${oldValue},新值为${newValue}`)})
</script>

2.侦听多个数据

<script setup>// 1. 导入watchimport { ref, watch } from 'vue'const count = ref(0)const name = ref('cp')// 2. 调用watch 侦听变化watch([count, name], ([newCount, newName],[oldCount,oldName])=>{console.log(`count或者name变化了,[newCount, newName],[oldCount,oldName])})
</script>

3.immediate和deep参数

<script setup>// 1. 导入watchimport { ref, watch } from 'vue'const count = ref(0)// 2. 调用watch 侦听变化watch(count, (newValue, oldValue)=>{console.log(`count发生了变化,老值为${oldValue},新值为${newValue}`)},{immediate: true, // 侦听器创建出来之后立即执行一次deep: true // watch默认是浅层监听,对象内部的属性发生变化时不会触发,开启deep后即可监听内部属性})
</script>

3.5.生命周期函数

1.选项式对比组合式

2.生命周期函数的使用

<scirpt setup>
// 1.导入生命周期函数
import { onMounted } from 'vue'
// 2.定义生命周期函数,编写自定义逻辑
onMounted(()=>{// 自定义逻辑
})
</script>

相同的生命周期函数可以定义多个,会按照定义的顺序执行

<scirpt setup>
import { onMounted } from 'vue'
onMounted(()=>{// 自定义逻辑
})onMounted(()=>{// 自定义逻辑
})
</script>

3.6.父子组件的通信

1.父传子

2.子传父

3.7.模版引用

<script setup>
import { ref } from 'vue'
// 1.调用ref函数得到ref对象
const h1Ref = ref(null)
</script><template><!--- 2.通过ref标识绑定ref对象 --><h1 ref="h1Ref">我是dom标签</h1>
</template>

3.8.provide和inject

provide和inject用来跨层传递数据和方法。

//在顶层组件中使用 provide 来传递数据
<template><div><Child /></div>
</template><script setup>
import { provide } from 'vue';
import Child from './Child.vue';// 提供数据给子组件
provide('myData', 'Hello from Parent!');const setCount = () => {count.value++
}
// 提供方法给子组件
provide('setCount-key', setCount);
</script>
//在底层组件中使用 inject 来接收数据
<template><div><p>{{ myData }}</p></div>
</template><script setup>
import { inject } from 'vue';// 注入顶层组件提供的数据
const myData = inject('myData');// 注入顶层组件提供的方法
const setCount = inject('setCount-key')
</script>

4.宏函数

4.1.defineExpose

默认情况下在 <script setup> 语法糖下组件内部的属性和方法是不开放给父组件访问的,可以通过 defineExpose 编译宏指定哪些属性和方法容许访问。

4.2.defineOptions

使用 setup 函数的时候,如果要定义 props, emits,可以轻而易举地添加一个与 setup 平级的属性。但是,用了 <script setup> 后,就没法添加与其平级的属性了。

为了解决这一问题,在 Vue 3.3 中新引入了 defineOptions 宏,用来定义 Options API 的选项。可以用 defineOptions 定义任意的选项。

<script setup>
defineOptions({name:'组件名',inheritAttrs: false,// ... 更多自定义属性
})
</setup>

props、emits、expose、slots 这些除外,这些是使用对应的宏函数 defineXXX 来做到。

4.3.defineModel

在 Vue3 中,父组件在子组件上使用 v-model 进行双向数据绑定,相当于给子组件传递一个 modelValue 属性,同时监听并触发来自子组件的 update:modelValue 事件。

在子组件中,我们需要先定义 props,再定义 emits,会非常麻烦,并且会有许多重复的代码。

<scirpt setup>
import MyInput from '@/components/my-input.vue'
import { ref } from 'vue'
const txt = ref('123456')
</script><template>
<div><MyInput v-model="txt"></MyInput>{{ txt }}
</div>
</template>
<scirpt setup>
defineProps({modelValue: String
})
const emit = defineEmits(['update:modelValue'])
</script><template>
<div><inputtype="text":value="modelValue"@input="e => emit('update:modelValue', e.target.value)">
</div>
</template>

有了 defineModel 之后,读取和修改父组件的属性会非常简单,如下所示:

<script setup>
const modelValue = defineModel()
// 修改父组件的属性
modelValue.value++
</setup><template>
<!--读取父组件的属性-->
<div>{{ modelValue }}<div>
</template>

需要注意的是,生效需要配置 vite.config.js。

import { fileURLToPath, URL } from 'node:url'import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'// https://vitejs.dev/config/
export default defineConfig({plugins: [vue({script: {defineModel: true}}),],resolve: {alias: {'@': fileURLToPath(new URL('./src', import.meta.url))}}
})

5.Pinia

5.1.什么是Pinia

Pinia 是 Vue3 的状态管理库 ,是 Vuex 状态管理工具的替代品。

5.2.Pinia的使用

实际开发项目的时候,Pinia 可以在项目创建时自动添加。因为现在是初次学习,所以从零开始:

安装 Pinia

yarn add pinia
# 或者使用 npm
npm install pinia

创建 Pinia 实例并将其传递给应用

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'const app = createApp(App)
const pinia = createPinia()app.use(pinia)
app.mount('#app')

定义Store

import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useCounterStore = defineStore('counter', () => {//数据const count = ref(0)//修改数据的方法const increment = () => {count.value++}//以对象形式返回return { count, increment }
})

组件使用store

<script setup>
// 1.导入 useCounterStore 方法
import { useCounterStore } from '@/store/counter'
// 2.执行方法得到counterStore对象
const counterStore = useCounterStore()
</script><template><button @click="counterStore.increment">{{ counterStore.count }}</button>
</template>

5.3.computed

Pinia 中的 computed 函数用于定义计算属性,相当于 Vuex 中的 getters。

import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useCounterStore = defineStore('counter', () => {//数据const count = ref(0)//定义getterconst doubleCount = computed(() => count.value * 2)//以对象形式返回return { count, doubleCount }
})

5.4.action

pinia 中的 action 相当于组件中方法,直接定义即可。

export const useCounterStore = defineStore('main', {//数据const count = ref(0)// 同步actionconst addCount = increment() {this.count++}// 异步actionconst getList = async () => {const res = await axios.get('URL')console.log(res)}return {count,addCount,getList}
}
})

5.5.storeToRefs

在结构出 Pinia 中的数据时,像下面这样直接结构会丢失数据的响应式。

const { count, msg } = counterStore

storeToRefs 函数可以保证解析出的数据依然保持响应式

const { count, msg } = storeToRefs(counterStore)

5.6.Pinia持久化插件

Pinia中的数据进行持久化有专门的插件,具体使用步骤如下:

安装插件 pinia-plugin-persistedstate

npm i pinia-plugin-persistedstate

在 main.js 中配置

import { create } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
// 导入持久化的插件
import persist from 'pinia-plugin-persistedstate'// 创建Pinia实例
const pinia = createPinia()
// 创建根实例
const app = createApp(App)
// pinia插件的配置
app.use(createPinia().use(persist))
// 视图的挂载

配置 store/counter.js

import { defineStore } from 'pinia'
import { computed, ref } from 'vue'export const useCounterStore = defineStore('counter', () => {...return {count,doubleCount,increment}
}, {persist: true  // 开启持久化配置
})

http://www.mrgr.cn/news/83139.html

相关文章:

  • 掌握API和控制点(从Java到JNI接口)_38 JNI从C调用Java函数 01
  • Java 大视界 -- Java 大数据在智能金融监管中的应用与实践(77)
  • 【Leetcode刷题随笔】59 螺旋矩阵
  • Kubernetes 中 BGP 与二层网络的较量:究竟孰轻孰重?
  • grpc 和 http 的区别---二进制vsJSON编码
  • RabbitMQ 从入门到精通:从工作模式到集群部署实战(五)
  • docker+ffmpeg+nginx+rtmp 拉取摄像机视频
  • vs2022开发.net窗体应用开发环境安装配置以及程序发布详细教程
  • 创建基本的 Electron 应用项目的详细步骤
  • spark汇总
  • 【W800】UART 的使用与问题
  • 电脑硬盘系统迁移及问题处理
  • C# 特性
  • Qt 5.14.2 学习记录 —— 팔 QWidget 常用控件(3)
  • 个人博客搭建(二)—Typora+PicGo+OSS
  • 学习记录:C++基类构造函数的调用:理解和实践
  • selenium+pyqt5自动化工具总结
  • 夯实前端基础之HTML篇
  • 算法 -归并排序
  • 华为OD E卷(100分)50-预订酒店
  • 示波器Oscilloscope的使用方法
  • (长期更新)《零基础入门 ArcGIS(ArcScene) 》实验七----城市三维建模与分析(超超超详细!!!)
  • 学习记录:C++ 中 const 引用的使用及其好处
  • Spring AMQP-保证消费者消息的可靠性
  • 通俗易懂之线性回归时序预测PyTorch实践
  • 在 Ubuntu 22.04 上部署 AppArmor 应用安全教程