导航
npm i @vue/cli -g
vue create 项目名称

import { watch, ref, toRef, onMounted, computed } from 'vue';
// 在 setup 中使用 composition api
setup 的存在,就是为了能够在其中使用 Composition API
props 初始化完毕之后,beforeCreate 之前被调用


<template>
<div>{{ count }}</div>
</template>
<script>
export default {
name: 'App',
setup() {
return {
count: 0
}
},
}
</script>
<script>
import { ref, h } from 'vue';
export default {
name: 'App',
setup() {
const count = ref(0);
return () => h('h1', [count.value]);
}
}
</script>
<script>
export default {
name: 'App',
setup() {
return () => <div>123</div>;
}
}
</script>
setup 中解构 props ,会导致 props 被解构的值丧失响应式
setup({ title })const { title } = props父组件 App.vue
<template>
<div>
<Test :title="title" />
</div>
</template>
<script>
import { ref, h } from 'vue';
import Test from '@/components/Test';
export default {
name: 'App',
setup() {
const title = ref('Lance');
setTimeout(() => {
title.value = 'Lance233';
}, 1000);
return {
title
};
},
components: {
Test
}
}
</script>
子组件 Test.vue
<template>
<h1>{{ title }}</h1>
</template>
<script>
import { watch, watchEffect } from 'vue';
export default {
name: 'Test',
props: {
title: String
},
setup(props) {
console.log(props); // Proxy { title: 'Lance' }
watchEffect(() => {
console.log('title:', props.title); // 初始化Lance和变化后Lance233都能监听到
});
watch(() => {
return props.title; // 要监听的值
}, (newVal) => {
console.log('new Title:', newVal); // 只会监听变化后的值
});
}
}
</script>



如果你想要将一个对象的所有属性都当作 props 传入,你可以使用没有参数的v-bind,即只使用 v-bind 而非 :prop-name。例如,这里有一个 post 对象:
const post = {
id: 1,
title: 'My Journey with Vue'
}
以及下面的模板:
<BlogPost v-bind="post" />
而这实际上等价于:
<BlogPost :id="post.id" :title="post.title" />
setup(props, { attrs, slots })const { attrs, slots } = context<template>
<h1>{{ title }}</h1>
</template>
<script>
export default {
name: 'Test',
props: {
title: String
},
setup(props, context) {
console.log(context);
}
}
</script>
