[Vue3学习笔记] (二) setup ref reactive与生命周期
一、template不再需要根元素
显然在vue3中template不再一定需要一个父元素才能编译通过了。
二、setup函数初识
2.1、关于setup
setup函数其实是一个生命周期钩子,它对应的其实就是Vue2中的beforeCreate和create
在vue3中我们通过这个函数来定义vue2中的data,methods,watch,computed属性(数据定义与处理相关)
2.2、setup使用
setup函数必须有返回值,必须返回一个对象,对象里包含所有在template模板中需要使用到的属性(包含data,methods等)
setup函数有一个props参数,用于接收props,也就是定义在组件上的属性(同vue2),但是接收的props必须先在props属性中定义,否则是不会被接收到的
下面是一个setup的使用示例:
<template>
<h1>{
{ msg }}</h1>
<button @click="count++">count is: {
{ count }}</button>
</template>
<script>
import { ref } from "vue";
export default {
name: "HelloWorld",
props: {
msg: String,
},
setup(props) {
console.log(props); // Proxy{msg:...}
const count = ref(0);
return {
count,
};
},
};
</script>
我们在这里通过ref函数定义了一个变量count,ref函数是一个把普通变量变成Proxy响应式变量的函数。
三、使用 ref & reactive 使得数据经过变成Proxy响应式数据
3.1、ref函数
使用示例:
setup(props) {
// 使用示例
const count = ref(0);
return {
count,
};
},
用ref定义的变量,如果需要取到其变量值,需要使用.value
属性
比如:
setup(props) {
// 使用示例
const count = ref(0);
const changeCount = ()=>{
count.value++;
}
return {
count,
};
},
我们用changeCount
替代上述setup示例模板的count++
<template>
<h1>{
{ msg }}</h1>
<button @click="changeCount">count is: {
{ count }}</button>
</template>
有着相似的作用
ref的另一个用法:
调用原生DOM
<template>
<div ref