使用 vite 创建项目,以及 vue3 的 composition API 的使用
一、创建项目(vue-cli + vite)
使用 vite 可以更加快速的启动项目
1 2 3 4 5
| npm init vite-app <project-name>
cd project-name
npm install && npm run dev
|
二、main.js
1 2 3 4 5
| import { createApp } from "vue"; import App from "./App.vue"; import "./index.css";
createApp(App).mount("#app");
|
三、组合式 API:composition API
composition api 为 Vue 应用提供更好的逻辑复用和代码组织。
setup()钩子是在组件中使用组合式 API 的入口,通常只在以下情况下使用:
1、需要在非单文件组件中使用组合式 API 时。
2、需要在基于选项式 API 的组件中集成基于组合式 API 的代码时。
(一)、基本使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <script> import { ref } from 'vue'
export default { setup() { const count = ref(0)
return { count } },
mounted() { console.log(this.count) } } </script>
|
1 2 3
| <template> <button @click="count++">{{ count }}</button> </template>
|
Tip: setup() 自身并不含对组件实例的访问权,即在 setup() 中访问 this 会是 undefined。你可以在选项式 API 中访问组合式 API 暴露的值,但反过来则不行。
(二)、创建响应式对象
方法1、
1 2
| <p>{{ data.counter }}</p> <p>{{ data.doubleCounter }}</p>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| import { computed,reactive,onMounted,onUnmounted,ref,toRefs,watch} from "vue";
export default { setup() { const data = reactive({ counter: 1, doubleCounter: computed(() => data.counter * 2), });
const msg1 = ref("some message");
}, let timer; onMounted(() => { timer = setInterval(() => { data.counter++; }, 1000); }); onUnmounted(() => { clearInterval(timer); }); return { data, msg1 }; }, };
|
方法 2:toRefs:解构/展开返回响应式对象
1 2 3 4
| <p>{{ msg1 }}</p> <p>{{ counter }}</p> <p>{{ doubleCounter }}</p> <p ref="desc"></p>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| import { computed,reactive,onMounted,onUnmounted,ref,toRefs,watch} from "vue"; export default { setup() { const { counter, doubleCounter } = useCounter();
const msg1 = ref("some message");
const desc = ref(null);
watch(counter, (val, oldVal) => { const p = desc.value; p.textContent = `counter change from ${oldVal} to ${val}`; }); return { counter, doubleCounter, msg1, desc }; }, };
function useCounter() { const data = reactive({ counter: 1, doubleCounter: computed(() => data.counter * 2), });
let timer; onMounted(() => { timer = setInterval(() => { data.counter++; }, 1000); }); onUnmounted(() => { clearInterval(timer); }); return toRefs(data); }
|
(三)、单值响应式声明:ref
1
| const msg1 = ref("some msg");
|