<script type="module">
import {
createApp } from './node_modules/vue/dist/vue.esm-browser.js'
const app = createApp({
})
app.mount('#app')
script>
在props解析完毕之后组件实例创建之前执行. 所以在setup中无法获取组件实例的this,data,computed,method
<script type="module">
import {
createApp} from './node_modules/vue/dist/vue.esm-browser.js'
const app = createApp({
setup (props,context) {
const position = {
x: 0,y: 0};
return {
position}
},
})
app.mount('#app')
</script>
reactive返回一个代理对象
<script type="module">
import {
createApp} from './node_modules/vue/dist/vue.esm-browser.js'
const app = createApp({
setup (props,context) {
const position = reactive({
x: 0,y: 0});
return {
position}
},
})
app.mount('#app')
</script>
ref函数能把基本类型的数据转换成响应式数据
原理:把基本类型数据转换成具有value属性并具有get和set的响应式对象({value:0}
),如果ref传入的是一个对象那么就是调用reactive.
<script type="module">
import {
createApp, ref } from './node_modules/vue/dist/vue.esm-browser.js'
function useCount () {
const count = ref(0)
return {
count,
increase: () => {
count.value++
}
}
}
createApp({
setup () {
return {
...useCount()
}
}
}).mount('#app')
</script>
toRefs函数把代理对象中的所有属性都转换成响应式对象.
<script type="module">
import {
createApp, reactive, toRefs } from './node_modules/vue/dist/vue.esm-browser.js'
function useMousePosition () {
const position = reactive({
x: 0,
y: 0
})
return toRefs(position)
}
createApp({
setup () {
const {
x, y } = useMousePosition()
return {
x,
y
}
}
}).mount('#app')
</script>
const position = {
x: 0,y: 0}=>{
x:position.x,y:position.y}
computed创建响应式数据,这个响应式数据依赖于其它响应式数据,当依赖的数据变化后会重新计算属性传入的函数
<script type="module">
import {
createApp, reactive, computed } from './node_modules/vue/dist/vue.esm-browser.js'
const data = [
{
text: '看书', completed: false },
{
text: '敲代码', completed: false },
{
text: '约会', completed: true }]
createApp({
setup () {
const todos = reactive(data)
const activeCount = computed(() => {
return todos.filter(item => !item.completed).length
})
return {
activeCount,
push: () => {
todos.push({
text: '开会',completed: false})
}
}
}
}).mount('#app')
</script>
watch的三个参数
watch的返回值
<div id="app">
<p>
请问一个 yes/no 的问题:
<input v-model="question">
</p>
<p>{
{
answer }}</p>
</div>
import {
createApp, ref, watch } from './node_modules/vue/dist/vue.esm-browser.js'
createApp({
setup () {
const question = ref('')
const answer = ref('')
watch(question, async (newValue, oldValue) => {
const response = await fetch('https://www.yesno.wtf/api')
const data = await response.json()
answer.value = data.answer
})
return {
question,answer}
}
}).mount('#app')
WatchEffect
<script type="module">
import {
createApp, ref, watchEffect } from './node_modules/vue/dist/vue.esm-browser.js'
createApp({
setup () {
const count = ref(0)
const stop = watchEffect(() => {
console.log(count.value)
})
return {
count,
stop,
increase: () => {
count.value++
}
}
}
}).mount('#app')
</script>
项目浏览地址
github源码地址