vue3入门指南
创建项目
npm init vite-app demo (demo是项目的名字)
cd demo
npm i
npm run dev
目录结构说明
│ index.html 单页面HTML文件
│ package-lock.json 记录安装时的包的版本号,以保证自己或其他人在 npm install 时大家的依赖能
│ package.json 包说明文件,记录了项目中使用到的第三方包依赖信息等内容
│
├─public
│ favicon.ico 浏览器图标
│
└─src
│ App.vue 根组件,最终被替换渲染到 index.html 页面中 #app 入口节点
│ index.css 全局样式文件
│ main.js 整个项目的启动入口模块
│
├─assets
│ logo.png
│
└─components
HelloWorld.vue
vue3官方文档地址
vue根实例
const RootComponent = { /* options */ }
const app = Vue.createApp(RootComponent)
const vm = app.mount('#app')
新版生命周期
创建全局指令
import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
const app = createApp(App)
app.directive('my-directive',{
beforeMount(el){
el.style.color = 'blue'
},
mounted(el){
el.focus()
},
beforeUpdate(){},
updated(){},
beforeUnmount(){},
unmounted(){}
})
app.mount('#app')
组合式语法
我们之前的语法逻辑分布在watch,computed,directive等各个概念当中,在vue3当中,我们可以全部写在setup当中,我们称之为组合式语法
<template>
<div>
<button @click="add">按钮</button>
<h3>{{state.count}}</h3>
<h1>{{double}}</h1>
</div>
</template>
<script>
import {reactive,ref,onMounted,computed} from 'vue'
export default {
// composition 的入口函数,在beforeCreate 之前调用。返回值作为模板渲染的上下文。
setup(){
//reactive将对象封装成响应式
const state = reactive({count:1});
//ref将值类型打包成响应式对象
const num = ref(1);
function add(){
state.count++;
num.value += 10;
}
const double = computed(()=>state.count * 2)
return {
state,add,double,num
}
}
}
</script>
<style scoped >
</style>
Teleport
渲染组件到指令DOM节点,做弹框比较有用
<template>
<Teleport to="body">
<div class="dialog">
弹框
</div>
</Teleport>
</template>
<script>
export default {
data () {
return {
}
},
methods: {
}
}
</script>
<style scoped >
.dialog{
width:200px;
height:200px;
background: #ccc;
position:fixed;
left:50%;
top:50%;
transform: translate(-50%,-50%);
}
</style>
配置路由
npm docs vue-router@next
import {createRouter,createWebHashHistory} from 'vue-router'
const router = createRouter({
history:createWebHashHistory(),
routes:[
{path:'/',redirect:'/home'},
{path:'/home',name:'home',component:()=>import('./views/Home.vue')},
{path:'/about',name:'about',component:()=>import('./views/About.vue')}
]
})
export default router
配置vuex
npm install vuex@next
import {createStore} from 'vuex'
export default createStore({
state:{
test:{
a:1
}
},
mutations:{
setTestA(state,value){
state.test.a = value
}
},
actions:{},
modules:{}
})
相关代码
https://gitee.com/js-class/vue3_intro