1.vue3在组件模板<template />中,不需要跟根节点<div />
2.vue2是直接把vue选项对象暴漏出去,vue3通过dafineComplate传入组件,生成一个vue实例
3.vue2是选项式api,所以,我们把所有的methods,data,watch,computed等等,都放在vue实例下面
而vue3是一个组合式api,所有的这些东西,都放在setup中, setup(){}包括所有data,methods,created,complate都在里面,setup里面内容需要全部暴露出去才能使用,比如数据和函数,setup在所有组件执行之前会执行,且只执行一次
<template>
<div>
<h1 >{
{color}}</h1>
<button @click="change">改变了</button>
</div>
</template>
<script lang="ts">
import { defineComponent, ref, watch, reactive } from "vue";
export default defineComponent({
setup() {
let color=ref<string>('red');
function change(){
//使用ref包裹变量 此时的color 已经变成了一个对象
color.value='green'
console.log('aaa');
}
return {
color,
change
}
}
});
</script>
<style scoped>
</style>
4.vue3中的setup里面数据需要用ref修饰改为响应式数据才能跟外面数据同时变化,这时候color成为一个对象,要改变值需要用color。value
vue2data里的数据可以直接使用,也是同时变化的
ref也可以来自动获取焦点
<template>
<div>
<h2>ref获取页面元素焦点</h2>
<input type="text"><br>
<input type="text" ref="inputRef">
</div>
</template>
<script lang="ts">
import {defineComponent,onMounted,ref} from 'vue';
export default defineComponent({
name:'HQHD',
setup(){
const inputRef=ref<HTMLElement|null>(null)
onMounted(()=>{
inputRef.value && inputRef.value.focus();//自动获取焦点
})
return{
inputRef
}
}
})
</script>
<style scoped>
</style&