vue3.0已經發布好久了,做爲一個靠vue吃飯的程序員,真心表示學不動了。。。前幾天看了一些關於3.0的視頻,今天總結一下vue3.0項目建立的幾種方式,以及demo。vue
第一種:vue-cli建立以後引入vue-next或者3.0中想要體驗的api,代碼以下:react
1.直接引入vue-next
vue create vue3.0-demo-cli
vue add vue-next
2.引入3.0的composition-api 使用這一部分功能
vue create vue3.0-demo-cli
vue add @vue/composition-api
// main.js 中引入
import VueCompositionApi from '@vue/composition-api'
Vue.use(VueCompositionApi);複製代碼
直接引入vue-next,要注意vue-cli的版本,若是版本低於4.0則要升級vue腳手架:npm install -g @vue/cli
,
不然項目運行時會報錯。程序員
第二種:Vite 建立vue3.0,代碼以下:vue-cli
npm install -g create-vite-app // 全局安裝vitecreate-vite-app vue-demo-vite複製代碼
vite建立項目飛快,嗯,尤大很看好,利用了瀏覽器自帶的import功能,不管項目多複雜,啓動都是O(1)npm
HelloWorld.vue
<template>
<div class="hello">
{{top}}
<input :class="{fixedinput:top>10}"
type="text"
v-model="state.newTodo" @keyup.enter="addTodo">
<div>
<span>{{nums}}</span> <span @click="add" >點擊</span>
</div>
<ul>
<li :class="{done:todo.status}"
v-for="(todo,index) in state.todoList"
:key="todo.id"
@click="toggle(index)">
{{todo.name}}</li>
</ul>
<div>
完成事件個數:{{remain}}
</div>
</div>
</template>
<script>
import { ref, reactive, computed } from 'vue'
// 若是沒有import 打包能夠把代碼丟掉 tree-shaking
// compisition 能夠拆開獨立函數放在獨立文件 vue只能用mixin 會找不到源頭 以及重名
import addTodoFac from './hello_function'
// 拆分複雜邏輯import useScrollFac from './hello_function_userScroll'
export default {
setup () {
const nums = ref(0)
const add = () => {
nums.value += 1
}
const state = reactive({
newTodo: '',
todoList: [
{ id: 0, name: '學習', status: false },
{ id: 1, name: '吃飯', status: true },
{ id: 2, name: '睡覺', status: false }
]
})
// 函數能夠抽離出去 拆包 拆成獨立函數
// function addTodo () {
// state.todoList.push(
// { id: state.todoList.length, name: state.newTodo, status: false }
// )
// }
const { addTodo } = addTodoFac(state)
function toggle (index) {
state.todoList[index].status = !state.todoList[index].status
}
const { top } = useScrollFac()
console.log(top)
const remain = computed(
() => state.todoList.filter(todo => todo.status).length
)
return {
nums,
add,
state,
addTodo,
remain,
toggle,
top
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
margin: 20px 10px;
}
li.done{
text-decoration: line-through;
}
.fixedinput{
position:fixed;
top:10px;
left:45%;
}
a {
color: #42b983;
}
</style>
// hello_function_userScroll.js
import { ref, onMounted, onUnmounted } from 'vue'
export default function useScroll () {
const top = ref(0) function upDate (e) {
top.value = window.scrollY
}
onMounted(
() => {
window.addEventListener('scroll', upDate)
}
)
onUnmounted(
() => {
window.removeEventListener('scroll', upDate)
}
)
return { top }
}
// hello_function.js
export default function (state) {
function addTodo () {
state.todoList.push(
{ id: state.todoList.length, name: state.newTodo, status: false }
)
}
return { addTodo }
}
複製代碼