Vue3 - 初识

create-vue

create-vue是Vue官方新的脚手架工具,底层切换到了 vite (下一代前端工具链),为开发提供极速响应

安装 & 创建项目

前置环境条件 :已安装16.0或更高版本的Node.js(node -v)

node.js 版本检查

node -v

安装 & 执行 create-vue

npm init vue@latest

目前还没到项目,选项可以一路 no(ESlint 可以 yes)

cd 项目名
npm install
npm run dev

Volar插件

vue3 的插件

禁用 Vetur (vue2)

熟悉项目和关键文件

image-20240202231929775.png

改变

script 放到了最上面
加上setup允许在其中直接编写组合式 API

template 不再要求唯一根元素

……

组合式API - setup 选项

组合式API 的入口,写了setup才能写组合式API

执行时机:在beforeCreate钩子之前执行

setup函数中,this是undefined

在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>
  const message = 'this is message'
  const logMessage = ()=>{
    console.log(message)
  }
</script>

组合式API - reactive

接受 对象类型 数据的参数传入并返回一个响应式的对象

<script setup>
 // 导入
 import { reactive } from 'vue'
    
 const state = reactive({
   count:100
 })
 const setCount = ()=>{
   // 修改数据更新视图
   state.count++
 }
</script>

<template>
  {{ state.count }}
  <button @click="setCount">change count</button>
</template>

组合式API - ref

接收 简单类型 或者 对象类型 的数据传入并返回一个响应式的对象

本质:是在原有传入数据的基础上,外层包了一层对象,包成了复杂类型

注意点:

  1. 脚本中访问数据,需要通过.value

  2. 在template中,.value不需要加(帮我们扒了一层)

<script setup>
 // 导入
 import { ref } from 'vue'

 const count = ref(0)
 
 const setCount = ()=>{
   // 脚本区域必须加上.value
   count.value++
 }
</script>

<template>
    结构不需用 .value
  <button @click="setCount">{{count}}</button>
</template>

reactive 和 ref

  1. 都是用来生成响应式数据
  2. 不同点
    1. reactive不能处理简单类型的数据
    2. ref参数类型支持更好,但是必须通过.value做访问修改
    3. ref函数内部的实现依赖于reactive函数
  3. 推荐使用 ref

组合式API - computed

<script setup>
// 导入
import {computed } from 'vue'
    
// 计算属性
const computedState = computed(() => {
    return 基于响应式数据做计算之后的值
})

也支持 get set

组合式API - watch

侦听一个或者多个数据的变化,数据变化时执行回调函数,

第三个参数 immediate控制立刻执行

deep开启深度侦听

侦听单个数据

<script setup>
  // 1. 导入watch
  import { 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>

immediate

在侦听器创建时立即出发回调

以对象的形式写

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

组合式API - deep

通过watch监听的ref对象默认是浅层侦听的,直接修改嵌套的对象属性不会触发回调执行,因为复杂类型的地址没有改变,所以浅层无法侦听里面的数据变化,除非改变地址:如,userInfo.value ={name:'ls',age:5θ}>

<script setup>
  // 1. 导入watch
  import { ref, watch } from 'vue'
  const state = ref({ count: 0 })
  
  // 2. 监听对象state 并开启deep
  watch(state, ()=>{
    console.log('数据变化了')
  },{
      deep:true
  })
    
  const changeStateByCount = ()=>{
    // 此时修改可以触发回调
    state.value.count++
  }
</script>

精确侦听对象的某个属性

const info = ref({
    name:'cp',
    age:18
})

watch(
    () => info.value.age,
    (newValue,oldValue) => console.log('age发生变化了',newValue,oldValue)
)

组合式API - 生命周期函数

生命周期函数对比

beforeCreate 和 created 的相关代码,一律放在 setup 中执行

如果有些代码需要在mounted生命周期中执行

onMounted(()=>{
    console.log('mounted生命周期函数-逻辑1')
}

写成函数的调用方式,可以调用多次,并不会冲突,而是按照顺序依次执行

<scirpt setup>
import { onMounted } from 'vue'
onMounted(()=>{
  
})

onMounted(()=>{
  
})
</script>

组合式API - 父子通信

父传子

  1. 父组件中给子组件绑定属性
  2. 子组件内部通过props选项接收数据

父组件中

<script setup>
    //引入子组件
    import sonComVue from './son-com.vue'
</script>

<template>
    <!-- 1。绑定属性 message -->
    <soncomVue message="this is app message"
</template>

子组件中

<script setup>
    // 由于写了 setup,所以无法直接配置 props 选项
    // 2.通过 defineProps“编译器宏”接收子组件传递的数据
    const props = defineProps({
        message: String
    })
    // JS 使用
    console.log(props.car)
    
</script>

<template>
    <!-- 对于 props 传递过来的数据,模板中可以直接使用 -->
    {{ message }}
</template>

子传父

  1. 父组件中给子组件标签通过@绑定事件
  2. 子组件内部通过emit方法触发事件

父组件中

<script setup>
    // 引入子组件
    import sonComVue from './son-com.vue'
    const 修改数据的函数名 =(msg) =>{
        console.log(msg)
    }
</script>

<template>
    <!--1.子组件绑定自定义事件-->
    <sonComVue @自定义事件名="修改数据的函数名" />
</template>

子组件中

<script setup>
    // 2. 通过 defineEmits编译器宏 生成emit方法
    const emit = defineEmits(['自定义事件名'])
    
    const 传给父组件修改数据的函数名 =() =>{
        // 3. 触发自定义事件 并传递参数
        emit('自定义事件名',传递参数)
    }
</script>

<template>
    <button @click="传给父组件修改数据的函数名">sendMsg</button>
</template>

组合式API - 模版引用

通过 ref 获取真实的 dom对象或者组件实例对象

通过ref对象.value即可访问到绑定的元素(必须渲染完,才能拿到)

获取 dom 对象

<script setup>
    import { onMounted,ref } from 'vue'
    // 1。 调用ref函数得到ref对象
    const 名字 = ref(null)
    
    // 通过ref对象.value即可访问到绑定的元素(必须渲染完,才能拿到)
    onMounted(()=>{
        console.log(inp.value)
        inp.value.focus()
    })
</script>

<template>
    <!-- 2. 通过ref标识 绑定ref对象 -->
    <input ref="名字" type='text'>
    
</template>

获取组件

<script setup>
    import { TextCom } from ''
    import { onMounted,ref } from 'vue'
    // 1。 调用ref函数得到ref对象
    const 名字 = ref(null)
    const getCom = () => {
        console.log(textRef.value)
        textRef.value.count
        textRef.value.sayHi()
    }
</script>

<template>
    <!-- 2. 通过ref标识 绑定ref对象 -->
    <TextCom ref="名字"></TextCom>
    <button @click="getCom">获取组件</button>
</template>
defineExpose

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

组件内

<script>
    const count = 0
    const sayHi = () =>{
        console.log('hi')
    }
    defineExpose{
        count,
        sayHi
    }
</script>

组合式API - provide和inject

顶层组件向任意的底层组件传递数据和方法,实现跨层组件通信

传递

顶层组件中

<script>
    import 组件 from ''
    import { provide,ref } from 'vue'
    
    // 普通数据
    provide('名字',传递的数据)
    
    //响应式数据
    const count = ref(100)
    provide('count',count)
</script>

底层组件中

<script>
    import { inject } from 'vue'
    
    const 变量 = inject('名字')
    
    const cout = inject('count')
</script>

底层修改数据

传递函数,给子孙后代传递可以修改数据的方法

顶层组件中

<script>
    import 组件 from ''
    import { provide,ref } from 'vue'
    
    const count = ref(100)
    provide('count',count)
    
    provide('changeCount',(newCount)=>{
        count.value = newCount
    })
</script>

底层组件中

<script>
    import { inject } from 'vue'
    
    const cout = inject('count')
    
    const changeCount = inject('changeCount')
    const clickFn =()=>{
        changeCount(1000)
    }
</script>

Vue3.3 新特性 - defineOptions

有 <script setup> 之前,如果要定义 props, emits 可以轻而易举地添加一个与 setup 平级的属性。
但是用了 <script setup> 后,就没法这么干了 setup 属性已经没有了,自然无法添加与其平级的属性。

为了解决这一问题,引入了 defineProps 与 defineEmits 这两个宏。但这只解决了 props 与 emits 这两个属性。

如果我们要定义组件的 name 或其他自定义的属性,还是得回到最原始的用法——再添加一个普通的 <script> 标签。但这样就会存在两个 <script> 标签。让人无法接受。

所以在 Vue 3.3 中新引入了 defineOptions 宏。顾名思义,主要是用来定义 Options API 的选项。

可以用 defineOptions 定义任意的选项, props, emits, expose, slots 除外(因为这些可以使用 defineXXX 来做到)

<script setup>
    defineOptions({
        name:'',
        ...
    })
</script>

Vue3.3新特性 - defineModel

实验性的特性

在Vue3中,自定义组件上使用v-model, 相当于传递一个modelValue属性,同时触发 update:modelValue 事件

父组件中

<Child v-model='isVisible'>
// 相当于
<child :modelValue='isVisible' @update:modelValue='isVisible=$event'>

需要先定义 props,再定义 emits 。其中有许多重复的代码。如果需要修改此值,还需要手动调用 emit 函数。于是乎 defineModel 诞生了。

<script setup>
    const modelValue = defineModel()
    modelValue.value++
</script>

生效需要配置 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))
    }
  }
})

重启一下架子

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容