Vue3的ref创建一个全局变量,非常好用!

70 阅读2分钟

1. 前言

  1. Vue3的ref对象我们都知道其用法,通过ref可以创建一个响应式对象使用,同时可以用compute,watch等Vue3的API对其进行操作

  2. 不同于Vue2的是,Vue3使用的是组合式API,这也就意味着,我可以在外部单独创建一个ref对象,然后保存,通过导出的方式,给其他的页面使用

  3. 理论存在,开始实践

2. demo实现

  1. 搭建框架 首先搭建一个Vue3+Vite的框架,不需要其他第三方库
yarn create vite
// 输入项目名称
// 选择技术栈 Vue JavaScript
  1. 删除多余的文件
  2. 创建两个vue组件

image.png

  1. 将两个组件导入到App.vue中
<template>
  <div>
    <com1></com1>
    <com2></com2>
  </div>
</template>

<script setup>
import com1 from './components/component1/index.vue';
import com2 from './components/component2/index.vue';
</script>

<style lang="scss" scoped></style>
  1. 创建一个公共的全局js文件
  2. 在这个全局的js文件中导入Vue3的ref对象
  3. 在这个全局的js中创建一个ref对象,并导出
import { ref } from 'vue'

export let count = ref(1)
  1. 在两个组件中引用这个导出的ref对象,组件1用来显示这个ref对象,组件2用来修改这个ref对象
// 组件1
<template>
  <div>
    {{ count }}
  </div>
</template>

<script setup>
import { count } from '../../utils/global';
</script>

<style lang="scss" scoped></style>

// 组件2
<template>
  <div>
    <button @click="changeCount">修改count</button>
  </div>
</template>

<script setup>
import { count } from '../../utils/global';
const changeCount = () => {
  count.value++;
};
</script>
  1. 结果就会发现,在组件2中修改count,组件1中的count也会实时变化,这是因为count本身就是一个响应式对象,并不会因为在不同的页面使用而导致丢失响应式,并且不仅可以像这样简单的修改和显示使用,还可以用于不同页面的computedwatch中,响应式的对象也不仅仅限于简单数据类型,可以传入对象,数组等复杂数据类型

3. 总结

以上就是本篇文章分享的全部内容了,对以上分享的内容有疑问的欢迎评论以及私信,我看到都会解答的,下篇文章见