Skip to content
鼓励作者:欢迎打赏犒劳

01-vue3学习整理

主要记录一下Vue3的知识

推荐博客:http://web.wiyp.top/#/Vue/VueBook33

变量

reactive 和 ref 是 Vue 3 中的两种响应式数据绑定方式,ref 适用于简单的响应式数据,而 reactive 则适用于复杂对象或数组的响应式数据。

ref:使用 .value 属性来访问和修改值。

reactive:可以直接访问和修改对象或数组的属性或元素,而无需使用 .value。

vue
import { ref, reactive } from 'vue';

// ref示例
const count = ref(0);
console.log(count.value); // 访问值
count.value += 1; // 修改值

// reactive示例
const state = reactive({
  name: 'Alice',
  age: 25,
});
console.log(state.name); // 访问属性
state.age += 1; // 修改属性

全局变量

在Vue 3中,由于不再直接暴露Vue构造函数,传统的通过Vue.prototype挂载全局方法的方式不再适用。取而代之的是,你可以使用应用的app.config.globalProperties来挂载全局方法

main.js 设置全局变量。

js
import { createApp } from 'vue'
const app = createApp(App);
 
/**定义变量$website,并赋值为devcursor**/
app.config.globalProperties.$website = '卡卡罗特';
app.config.globalProperties.$myGlobalMethod = function() {
    alert('This is a global method');
};

在模版使用

vue
<template>
  <div>{{ $website }}</div>
</template>

在js使用

shell
<script setup>
import { getCurrentInstance } from 'vue'

//获取方法1
const app = getCurrentInstance()
const website = app.appContext.config.globalProperties.$website
console.log(website)

//获取方法2
const app = getCurrentInstance()
const {$website,$myGlobalMethod} = app.appContext.config.globalProperties
console.log($website)
//方法执行
$myGlobalMethod()
 
//获取方法3
const { proxy } = getCurrentInstance()
console.log(proxy.$website)
</script>
shell
<script>
export default {
  name: 'HelloWorld',
  created() {
    alert(this.$website);
  },
}
</script>

组件传值

setup 语法糖

父传子-defineProps

主要是 用vue的 defineProps 来接收数据

父页面

vue
<Home :data2="[1,2]"/>

子组件 Home.vue

vue
<template>
    <div>
        我是子组件
    </div>
</template>
<script setup>
    import { defineProps } from 'vue'
    const props = defineProps({
        data2: {
            default: [],
            type: Array,
        },
    });
    console.log(props.data2)
</script>

子传父-defineEmits

javascript
// 子组件:创建自定义事件,传递数据
const emit = defineEmits(['自定义事件']);
emit('自定义事件', 数据1, 数据2);
 
// 父组件:绑定自定义事件,接收数据
<组件标签 @自定义事件="函数名"></组件标签>
 
const 函数名 = (参数1, 参数2) => {
  console.log(参数1, 参数2);
}

父组件

vue
<Home  @clickChild="clickEven"/>

<script setup>
    const clickEven=(val1,val2)=>{
      console.log(val1,val2);
    }
</script>

子组件

vue
<template>
    <div>
        <el-button type="primary" @click="alert2">按钮</el-button>
    </div>
</template>
<script setup>
    import { defineEmits  } from 'vue'
    // 使用defineEmits创建名称,接受一个数组
    const emit = defineEmits(['clickChild'])
    function alert2() {
        //传递给父组件
        let param={
            content:'b'
        }
        emit('clickChild',param,"cccc")
    }
</script>

父传孙

注意

正常情况下,父子组件之间的数据传递需要用到 props 属性,这里就会有问题,如果父组件的数据需要送到 N 层子组件, 那么就要传递 N 次 props 属性,非常繁琐,而 provide / inject 就是用来解决 props 多层嵌套的问题,有了它, 只需声明一次数据就够了,使用方式也很简单。

在组合式 API 中使用 provide/inject,两个只能在 setup 期间调用,使用之前,必须从 vue 显示导入 provide/inject 方法。

nvm

provide 函数接收两个参数:

provide( name,value )

name:定义提供 property 的 name 。

value :property 的值。

使用时:

js

import { provide } from "vue"
export default {
  setup(){
    provide('info',"值")
  }
}

inject 函数有两个参数:

inject(name,default)

name:接收 provide 提供的属性名。

default:设置默认值,可以不写,是可选参数。

js
import { inject } from "vue"
export default {
  setup(){
    inject('info',"设置默认值")
  }
}

完整实例1:provide/inject实例

vue
//父组件代码
<script>
import { provide } from "vue"
export default {
  setup(){
    provide('info',"值")
  }
}
</script>

//子组件 代码
<template>
 {{info}}
</template>
<script>
import { inject } from "vue"
export default {
  setup(){
    const info = inject('info')
    return{
      info
    }
  }
}
</script>

父直接获取子的属性

在 Vue 3 中,你可以使用 ref 属性在父组件中引用子组件实例,然后直接访问其内部的可公开的属性或方法。

子组件 (ChildComponent.vue):

vue
<template>
    <div>
        <!-- 子组件模板 -->
    </div>
</template>

<script>
    export default {
        setup() {
            const message = 'Hello from child';

            // 提供一个可以被父组件调用的方法
            const exposeMessage = () => message;

            return { exposeMessage };
        }
    }
</script>

父组件 (ParentComponent.vue):

vue
<template>
    <div>
        <child-component ref="childRef" />
        <button @click="fetchMessage">Get Message</button>
    </div>
</template>

<script>
    import { ref } from "vue"
    import ChildComponent from './ChildComponent.vue';

    export default {
        components: { ChildComponent },
        setup() {
            //注意:1:子组件需要声明一个固定的ref;  2:再定义一个同名ref变量接收
            const childRef = ref();

            const fetchMessage = () => {
                console.log(childRef.value.exposeMessage());
            };

            return { childRef, fetchMessage };
        }
    }
</script>

消息总线通信

比如兄弟组件的通信,我感觉很方便。

shell
yarn add mitt

utils/mitter.js

js
import mitt from 'mitt';

const mitter = mitt();

export default mitter;

X.vue

vue
<template>
    <button @click="getData()">获取数据</button>
</template>

<script setup>
    import mitter from '@/utils/mitter';

    function getData() {
        // 发送事件
        mitter.emit('eventName', "123");
    }
</script>

Y.vue

vue
<template>
    {{list}}
</template>

<script setup>
    import { ref  } from "vue";
    import mitter from '@/utils/mitter';

    let list = ref()

    // 监听事件
    mitter.on('eventName', (data) => {
        list.value = data
    });
</script>

声明变量

文档: https://cn.vuejs.org/guide/essentials/reactivity-fundamentals.html

shell
<script setup>
import { reactive } from 'vue'

const state = reactive({ count: 0 })
</script>

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

计算属性

shell
import { computed, reactive } from 'vue'

const state = reactive({
  count: 0
})

const doubleCount = computed(() => {
  return state.count * 2
})

console.log(doubleCount.value) // 输出:0

state.count = 1

console.log(doubleCount.value) // 输出:2

如何使用$refs

如何在 Vue3 的 setup 中使用 $refs

第一种

通过 ref() 函数,依然可以实现类似 this.$refs 的功能。

首先在 setup 中定义一个 Ref 变量,然后将这个 registerFormRef 变量挂载到 DOM 上

vue
<script setup>
import { ref } from 'vue'
const registerFormRef = ref()

registerFormRef.validate((valid) => {
    
})
</script>

<template>
   <el-form  ref="registerFormRef"></el-form>
</template>

第二种

通过 getCurrentInstance() 可以获得 vue 实例对象。

vue
<template>
    <el-form  ref="registerFormRef"></el-form>
</template>

<script setup>
    import {getCurrentInstance} from 'vue'

    const app = getCurrentInstance()

    function registerUser() {
      app.proxy.$refs.registerFormRef.validate((valid) => {
        if (valid) {
          // 业务逻辑
        }
      });
    }

</script>

如有转载或 CV 的请标注本站原文地址