1.setup函数
// 主要有两个参数
// props 父组件中传递过来的参数
// emit 组件内部需要出发事件的时候
// slots 父组件传递过来的插槽
// setup(props,context) {
props: {
msg: String,
},
setup(props, { attrs, slots, emit }) {
let {msg} = toRefs(props) // 可以使用进行解构赋值
let msg = toRef(props,'msg') //
console.log(props.msg, "父组件的传递的参数");
console.log(emit, "第二个参数");
console.log(slots, "第二个参数");
console.log(attrs, "第二个参数");
return{
count:'计数器'
}
},
2.reactive的使用
<script>
import { reactive } from "vue";
export default {
name: "HelloWorld",
props: {
msg: String,
},
setup() {
const state = reactive({
count: "技术",
});
return {
state
};
},
};
</script>
3.toRefs,customRef,toRef,ref的使用
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<h2>{{ count }}</h2>
<h2>{{ age }}</h2>
<button @click="jiaBtn()">加一个</button>
<input type="text" v-model="val1">
<h1>{{val1}}</h1>
</div>
</template>
<script>
import { reactive, toRefs, toRef } from "vue";
import refs from '../utils/ref'; // 自定义ref
export default {
name: "HelloWorld",
props: {
msg: String,
},
setup() {
// toRefs:将所有的reactive中的所有属性转化为ref对象,建立链接
// toRef:将其中一个的reactive中的所有属性转化为ref对象,建立链接
const val1 = refs('')
const info = reactive({ name: "张三", age: 18 });
const { name } = toRefs(info)
const age = toRef(info,"age")
const jiaBtn = ()=>{
age.value++;
}
return {
name,
val1,
age,
jiaBtn
};
},
};
</script>
// 自定义refs
import { customRef } from 'vue'
// 定义ref
export default function (value) {
let timer = null;
return customRef((track, trigger) => {
return {
get() {
track();
return value;
},
set(newValue) {
clearTimeout(timer)
timer = setTimeout(() => {
value = newValue;
trigger();
}, 1000)
}
}
})
}
4.computed和watch和watchEffect
<script>
import { ref, computed, watchEffect, watch } from "vue";
export default {
name: "HelloWorld",
setup() {
// 自动寻找对应的
const count = ref(10);
const age = ref(18);
const haha = ref(null);
// 计算属性
const sum = computed(() => count.value + age.value);
const jiaqilai = computed({
get: () => count.value + " " + age.value,
set: (val) => console.log(val),
});
const jiaBtn = () => {
count.value++;
age.value++;
};
// 监听属性
watchEffect(() => {
console.log("haha", haha.value);
},{
// 通过 flush:post可以避免副作用,在DOM更新后运行副作用,确保模板引用与DOM保持同步,并引入正确的元素。
flush: "post",
}
);
// 监听某个值
watch(() => count, (val) => {
if (val) {
console.log(val, 'val改变的值')
}
}, { immediate: true })
return {
count,
sum,
age,
haha,
jiaqilai,
jiaBtn,
};
},
};
</script>