学习目标:掌握Vue3的学习知识
学习内容:
1.setup(props, context){ }
setup 不能使用this 调用props传过来 直接props.XX
props: 父组件传递过来的值
context: 全局上下文 (attrs , slots , emit)
解构写法 setup( props,{attrs, slots ,emit}) {}
--------解构以后数据不是响应式数据---------
attrs:获取css属性,非prop的attribute(id class 等)slots:插槽 emit:子传父
2.reactive (转为proxy 来进行响应式处理)
传入类型必须是对象 或者 数组
<template>
<div>
{{state.count}}
</div>
</template>
<script>
import { reactive } from 'vue'
export default {
setup () {
const state = reactive({
count: 0,
})
return {
state,
}
}
}
</script>
3.ref?(推荐使用ref? ?)
ref返回一个可变的响应式对象,拥有一个value属性。在template自动解包,在setup里面不会自动解包,所以在setup中需要value属性
<template>
// 在template自动解包
<div>
{{count}}
</div>
</template>
<script>
import { ref } from 'vue'
export default {
setup () {
const count = ref(1)
return {
count,
}
}
}
</script>
4.readonly?(只读的? 只能使用不能修改)即使给它一个响应式对象也是只读,在给子组件传值的时候要用reactive 传响应式对象
<!-- -->
<template>
<div>
<el-button type="primary"
@click="inClick">+1</el-button>
<h1>{{count}}</h1>
<h1 v-if="loading">loading---</h1>
<img v-if="loaded"
:src="result.imgurl"
alt="">
<Suspense>
<shou-img />
</Suspense>
<el-button type="primary"
@click="OpenIsModal">打开</el-button>
<Modal :visible="ModalOpen"
@close-modal="OpenIsModalClose"> MOdal!!!</Modal>
</div>
</template>
<script lang= 'ts'>
import { ref, reactive, onMounted, watch, readonly } from "vue";
import useURLLoader from "./hooks/useURLLoader";
import Modal from "./hooks/Modal.vue";
import ShouImg from "./hooks/ShouImg.vue";
interface Result {
imgurl: string;
code: number;
}
export default {
components: {
Modal,
ShouImg,
},
setup() {
const info = reactive({ name: "shou" });
const readonly11 = readonly(info);
const inClick = () => {
readonly11.name = "111";
console.log(readonly11.name);
};
return {
count,
inClick,
result,
loading,
loaded,
ModalOpen,
OpenIsModal,
OpenIsModalClose,
};
},
};
</script>
<style lang='scss' scoped>
img {
width: 10px;
height: 10px;
}
</style>
5.toRefs? 可以使解构出来变量变为响应式,把reactive返回的对象中的属性都转换成ref
toRef 只转换一个变量为响应式?
let age = toRef( 对象, 'age')
const state =reactive({ name:"jia",age: 18 });
const { name, age } = state
const { name, age} = toRefs(state)
|