Vue3项目开发
搭建項目
npm init vite-app 項目名稱 npm run dev //運行項目命令聲明式渲染和命令式渲染
//聲明式 <template><h1>{{msg}}}</h1> </template><script>export default {name: 'App',data(){return {msg:'hello'}} }//命令式 document.querySelector("h1").innerHTML='xie'- v-once:內容只渲染一次
- v-html:使得內容可以插入html的代碼
- v-bind:綁定屬性的值,語法糖為:
- v-on:監聽事件,語法糖為@
動態參數
:[attributeName]="d" //attribute和d都是變量,需要在data中賦值監聽數據變化
//包含了兩個參數新值和舊值 watch:function(newVal,oldVal){}動態類名
<h1 :class="{active:isActive}"/> <button @click='toggleActive'/>export default{name:'app',data(){return {isActive:true }},methods:{toggleActive(){this.isActive=!this.isActive}} }<style scoped>.active{color:red; } </style>監聽事件傳參
//$event 為調用事件的對象 <button @click="btnClick($event,10)" />export default{data(){return {number:0 }},methods:{btnClick(event,num){this.number+=numconsole.log(event) }} }- v-model.lazy:當輸入失去焦點才會改變,相當于把input事件變為change事件
- v-model.lazy.number:將輸入轉化為數字
- v-model.trim:將輸入中的空格自動去除
watchEffect:立即執行里面的函數,并追蹤其響應式依賴,如果依賴發生改變,則再次調用該函數
watch:監聽特定的對象,回調函數參數為監聽對象的新值和舊值
//監聽多個源 watch([num,age],([newNum,Newage],[preNum,preAge])=>{})provide+inject組件通信
//需要傳值的組件 provide(傳過去的變量名,提供的變量) provide('student',student)//接收值的組件 inject(傳過來的變量名) const student=inject('student')匹配404頁面
const route=[{path:'/:path(.*)',component:()=>import() }]路由正則
//匹配id必須為數字 const route=[{path:'/article/:id(/\\d+)' }]//匹配多個參數 const route=[{path:'/article/:id+' }] //返回params.id為一個數組//*有沒有參數都可以 const route=[{path:'/article/:id*' }]//?有或沒有都可以,匹配0次或1次 const route=[{path:'/article/:id?' }]js實現路由跳轉
this.$router.push({path:'/about'})//攜帶參數跳轉 this.$router.push({name:'news',params:{id:798}})//替換頁面 this.$router.replace()//前進和后退 this.$router.go()vue3設置狀態管理
//vue3的狀態管理通過reactive+provide+inject實現 const store={state:reactive({message:'1' }),setMessage(val){this.state.message='2' } } //在全局中provide(store) //在需要使用公共狀態的地方inject['']fetch異步獲取資源
fetch(api).then(res=>res.json()).then(result=>{console.log(result) })vue3中使用axios進行前后端請求
axios.get(api).then(res=>{console.log(res)})vite配置跨域請求
在vite.config.js中配置
module.exports={proxy:{'/api':{target:'https://lol.qq.com/', //使用/api代理域名changeOrigin:true, //允許跨域rewrite:path=>path.replace('/^\/api/','')}} }//當axios發送請求碰到/api時,它會將其進行拼接:https://lol.qq.com//api/tft/js/component/global-component.js?v=20220624, //而通過設置重寫將/api變為空字符串:https://lol.qq.com/tft/js/component/global-component.js?v=20220624使用mock模擬數據
import Mock from 'mockjs'Mock.setup({timeout:'200-600' })Mock.mock('/api','get',()=>{return {//要返回的數據 } } )//mock正則匹配網址 Mock.mock(/\/api.*/, //即匹配/api,/api/隨便'get',()=>{return {//要返回的數據 } } )vuex狀態管理的使用
- state:存放數據
- getters:相當于computed
- mutations:修改狀態的方法 ,調用mutations中的方法使用this.$store.commit()
- actions:存放異步方法,調用actions中的方法使用this.$store.dispatch()
映射狀態數據和方法
import {mapActions,mapGetters,mapMutations,mapState} from 'vuex'computed:{...mapState(['count']) }總結