1.什么是选项式API?
答:选项式 API,我们可以用包含多个选项的对象来描述组件的逻辑,例如 data
、methods
和 mounted
。选项所定义的属性都会暴露在函数内部的 this
上,它会指向当前的组件实例。
2.选项式API的用法?
2.1选项式的依赖都写在data里面
2.2选项式的方法都写在methods里面
2.3选项式每次使用组件都需要先导出再导入使用
<template>
<div>
//写html结构或使用组件,或使用路由
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
data(){
return{
//依赖
}
},
mounted(){
//使用到的方法
}
})
</script>
<style scoped>
</style>
3.什么是组合式API?
答:组合式 API使用导入的 API 函数来描述组件逻辑。组合式 API 通常会与 <script setup> 搭配使用。
4.组合式API的用法?
4.1组合式的依赖和方法不分区域直接写在JavaScript的模块里。
4.2组合式的响应式依赖需要使用ref(基本数据),和reactive(引用数据)来实现数据的响应。
4.3需要使用什么就导入什么
<template>
<div>
//html结构
</div>
</template>
<script lang="ts">
import { defineComponent, reactive, ref,computed} from 'vue'//导入需要的东西
export default defineComponent({
setup () {
//写方法或者依赖 记得要return出去才能使用
const a=ref(1)
const obj=reactive({name:'zq',age:18})
function fn(){
}
const js=computed(()=>{
})
return {
a,obj,fn
}
}
})
</script>
<style scoped>
</style>
4.4 可以在JavaScript的模块使用setup属性,这样就不需要次次导出,直接导入就可以使用该vue组件啦。也不需要依赖和方法每次都要return出去才能使用。
<template>
<div>
<p>这是setup组合式的便利!homeview</p>
<router-link to="/about">跳转到about</router-link>
<input type="text" ref="input" value="hhhh">
<span>{{cba[0].name}}</span>
<button @click="fn">点击改变abc</button>
</div>
</template>
<script setup >
import { onMounted, ref,watchEffect,reactive} from 'vue';
const abc=ref(111)
const cba=reactive([
{name:'zq'}
])
const input = ref(null)
const fn=function(){
cba[0].name='xly'
}
onMounted(() => {
// console.log(input.value.value);
input.value.onchange = function () {
console.log(input
.value.value);
}
})
watchEffect(() => {
console.log(cba[0].name);
})
</script>
<style lang="scss" scoped></style>