setup:容许在script当中书写组合式API 并且vue3的template不再要求唯一的根元素
<script setup>const name = 'app';
</script>
组合式API的用法:
可以直接在script标签中定义变量或者函数,然后直接在template当中使用
<template>{{message}}<button @click="logMessage">log</button>
</template><script setup>
const message = 'this is message'
const logMessage = () =>{console.log("logMessage")
}</script>
响应式变量reactive的使用:
<template><button @click="setCount">{{state.count}}</button>
</template><script setup>
//导入函数
import {reactive} from 'vue'
//执行函数 传入一个对象类型的参数
const state = reactive({count:0
})const setCount = () =>{state.count++
}</script>
响应式变量ref的使用:
<template><button @click="setCount">{{count}}</button>
</template><script setup>
//导入函数
import {ref} from 'vue'
//执行函数 传入一个对象类型或者简单数据类型的参数
const count= ref(0)const setCount = () =>{count.value++
}</script>
computed计算属性
<template><div>原始响应式数据:{{list}}</div><div>计算属性数组{{computedList}}</div>
</template><script setup>//原始响应式import { ref } from 'vue'//导入computedimport { computed } from 'vue'const list = ref([1,2,3,4,5,6,7,8])//执行计算函数const computedList = computed(()=>{return list.value.filter(item=>item>2)})setTimeout(()=>{list.value.push(9,10)},3000)
</script>
watch函数:侦听一个或者多个数据的变化,数据变化时执行的函数。两个额外的参数1.immediate (立即触发) 2.deep(深度监听)
<template><div><button @click="setCount">+{{count}}</button></div>
</template><script setup>import {ref,watch} from 'vue'
const count = ref(0)
const setCount = () => {count.value++
}
watch(count,(newVal,oldVal)=>{console.log('count变化了',newVal,oldVal);
})</script>
watch监听对象数据的某一个属性:
<template><div><button @click="changeName">name:{{state.name}}</button><button @click="changeAge">age:{{state.age}}</button></div>
</template><script setup>import {ref,watch} from 'vue'
const state = ref({name:'cc',age:18
})
const changeName = () => {state.value.name='aa'
}
const changeAge = ()=>{state.value.age=20
}
//当只有age属性发生变化时才会触发回调函数
watch(() => state.value.age,() => {console.log('age变化了');}
)</script>
生命周期函数:
父组件给子组件传值:
1.父组件给子组件绑定属性
2.子组件内部通过props选项接收