Vite 創(chuàng)建Vue3項(xiàng)目及基礎(chǔ)使用

Vite 法語意為 "快速的"屡立,發(fā)音 /vit/话告,下一代前端開發(fā)與構(gòu)建的工具,等于現(xiàn)在的webpack泉粉。

第一感覺:npm run dev 的時(shí)候跑項(xiàng)目飛快

創(chuàng)建vue3項(xiàng)目

# npm 版本, 安裝vu3之前需要檢查npm版本號(hào)连霉,對(duì)號(hào)入座:
npm -v 

# npm 6.x
npm init vite@latest my-vue-app --template vue

# npm 7+, 需要額外的雙橫線:
npm init vite@latest my-vue-app -- --template vue

安裝依賴

npm i

運(yùn)行項(xiàng)目

npm run dev

VSC安裝vue3配套插件Volar

相信使用 vscode 和 vue2的同學(xué)對(duì) vetur 這個(gè)插件一定不會(huì)陌生。

認(rèn)識(shí)頁面 template script style

<script setup>


</script>

<template>
 
</template>

<style scoped>

</style>

從上面的代碼可以看到嗡靡,<script setup></script>標(biāo)簽和<template></template>標(biāo)簽順序已經(jīng)更換了跺撼,但我還是習(xí)慣vue2順序,且<script setup></script>標(biāo)簽中必須使用setup關(guān)鍵字定義讨彼。

vue3響應(yīng)式視圖更新數(shù)據(jù) ref

不同于vue的data和methods,vue3是這樣創(chuàng)建響應(yīng)式對(duì)象的歉井,在vue3中需要用到ref才能觸發(fā)視圖的更新。

<template>
    {{msg}}
    <button @click="changeName">更換名字</button>
</template>

<script setup>
import {ref} from 'vue'
let msg = ref('李白')
function changeName(){
    msg.value = '杜甫'
}
</script>
<template>
    {{user.username}}
    {{user.age}}
    <button @click="changeAge">更換</button>
</template>

<script setup>
import {ref} from 'vue'
let user = ref({
    username:'李白',
    age: 18
})
function changeAge(){
    user.value.age = 14
}
</script>

從上面2個(gè)demo來看点骑,我們vue3的數(shù)據(jù)響應(yīng)式需要如此來搞酣难,是不是發(fā)現(xiàn)似乎有些繁瑣谍夭?邏輯有些古怪?

響應(yīng)式reactive 取代ref憨募,恢復(fù)正常的寫法,相當(dāng)于vue2的data

<template>
    {{user.username}}
    {{user.age}}
    <button @click="changeName">更換</button>
</template>

<script setup>
import {reactive} from 'vue'
const user = reactive({
    username:'李白',
    age: 18
})
function changeName(){
    user.username = '王安石'
}
</script>

reactive解包寫法

<template>
    <button @click="changeName">更換</button>
    {{user.username}}
    {{user2.username}}
</template>

<script setup>
import {ref,reactive} from 'vue'

const user = ref({
    username:'李白',
})

const user2 = reactive(user.value)
function changeName(){
    user2.username = '杜甫'
}
</script>

這里關(guān)注到 {{user2.username}}


事件對(duì)象和傳遞參數(shù)

<template>
    {{user}}
     <button @click="changeName('江山',$event)">更換</button>
</template>

<script setup>
import {ref} from 'vue'
let user = ref('李白')
function changeName(username,event){
    user.value = username
    //console.log(event);
    console.log(username,event);
}
</script>

計(jì)算屬性

反序輸出字符串

<template>
    {{reMsg}}
</template>

<script setup>
import {ref,computed} from 'vue'
let msg = ref('hello')
const reMsg = computed(() => {
    return msg.value.split('').reverse().join('')
})
</script>

偵聽屬性

<template>
    {{msg}}
    {{user.name}}
</template>

<script setup>
import {ref,reactive,watch} from 'vue'
let msg = ref('hello')
let user = reactive({
    name:'雷柏',
    age: 20
})
watch(msg,(newValue,oldValue)=>{
    console.log(newValue);
    console.log(oldValue);
})
watch(
    ()=>user.name,
    (newValue,oldValue)=>{
    console.log(newValue);
    console.log(oldValue);
}
)
</script>

父子組件傳值:子組件用defineProps接收父組件傳過來的值

值得注意的是紧索,vue3中引入組件不在需要注入,直接Import 引入菜谣,使用即可
子組件

<template>
    {{title}} --- {{content}}
</template>

<script setup>
import { defineProps } from 'vue';
    const props = defineProps({
        title: String,
        content: String
    })
</script>

<style scoped>

</style>

父組件

<template>
    <HelloWorld :title="article.title" :content="article.content"></HelloWorld>
</template>

<script setup>
import HelloWorld from './components/HelloWorld.vue'
import { reactive } from 'vue';
let article = reactive({
    title: '滿江紅',
    content: '歲歲年年花相似'
})
</script>

父子組件傳值:子組件發(fā)布自定義事件珠漂,通知父組件修改值 defineEmits

子組件發(fā)布事件

<template>
    {{title}} --- {{content}}
    <button @click="btn">修改</button>
</template>

<script setup>
import { defineProps,defineEmits } from 'vue';
    const props = defineProps({
        title: String,
        content: String
    })
    const emit = defineEmits(['modifyContent','modifyTitle'])
    function btn(){
        emit('modifyContent')
        emit('modifyTitle')
    }
</script>

<style scoped>

</style>

父組件修改值

<template>
    <HelloWorld 
    :title="article.title" 
    :content="article.content"
    @modifyContent = "changeContent()"
    @modifyTitle = "changeTitle()"
    ></HelloWorld>
</template>

<script setup>
import HelloWorld from './components/HelloWorld.vue'
import { reactive } from 'vue';
let article = reactive({
    title: '滿江紅',
    content: '歲歲年年花相似'
})
function changeContent(){
    article.title = '秦時(shí)明月'
}
function changeTitle(){
    article.content = '巴山楚水凄涼地'
}
</script>


路由的創(chuàng)建與使用 vue3需要4.0版本的路由,store也是

安裝:

 npm i vue-router

創(chuàng)建路由腳本:src目錄下>創(chuàng)建router目錄>index.js



編寫腳本:/src/router/index.js

import {
    createRouter,
    createWebHashHistory,
    createWebHistory
} from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'
import Buycart from '../views/Buycart.vue'
const routes = [
    {
        path: '/home',
        component: Home,
        name: 'home'
    },
    {
        path: '/about',
        component: About,
        name: 'about'
    },
    {
        path: '/buycart',
        component: Buycart,
        name: 'buycart'
    },
    {
        path: '/product',
        component: () =>import('../views/Product.vue'),
        name: 'product'
    }
]

const router = createRouter({
    history: createWebHistory(), 
    routes,
})

export default router

main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index'
createApp(App).use(router).mount('#app') //use必須要在mount之前

路由使用

<template>
    <div>
        <router-view></router-view>
        <router-link to="/home">跳轉(zhuǎn)首頁</router-link>
      <button @click="router.push('/product')">跳轉(zhuǎn)至產(chǎn)品頁面</button>
      <button @click="goTo">跳轉(zhuǎn)至產(chǎn)品頁面</button>
    </div>
</template>

<script setup>
import { useRoute,useRouter } from 'vue-router';

let route = useRoute()
let router = useRouter()
function goTo(){
    console.log(route);
    router.push('/product')
}
</script>

<style scoped>

</style>

安裝vuex,需要下一代版本,官網(wǎng)默認(rèn)也是4.0x版本

npm i vuex@next --save

創(chuàng)建目錄/src/store/index.js

import { createStore } from 'vuex'

// 創(chuàng)建一個(gè)新的 store 實(shí)例
const store = createStore({
  state () {
    return {
      count: 0
    }
  },
  mutations: {
    increment (state,payload) {
      state.count += payload
    }
  },
  getters:{
      totalPrice(state) {
          return state.count*99.9
      }
  },
  actions:{
      asyncAdd(store,payload){
          setTimeout(()=>{
              store.commit('increment',payload)
          },1000)
      }
  }
})

export default store

main.js引入

import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index'
import store from './store/index'
createApp(App).use(router).use(store).mount('#app') //use必須要在mount之前

頁面使用

<template>
  <div>
      <h1>購物車</h1>
      <h2>商品數(shù)量{{store.state.count}}</h2>
      <h2>商品總價(jià){{store.getters.totalPrice}}</h2>
      <button @click="addProd">添加商品數(shù)量+2</button>
      <button @click="asyncAddProd">異步添加商品數(shù)量+10</button>
  </div>
</template>

<script setup>
import { useStore } from 'vuex';

let store = useStore()
function addProd(){
    store.commit('increment',2)
}
function asyncAddProd(){
    store.dispatch('asyncAdd',10)
}
</script>

suspense內(nèi)置新增組件尾膊,defineAsyncComponent異步封裝組件

調(diào)用組件

<template>
  <!-- suspense內(nèi)置新增組件,數(shù)據(jù)加載回來的時(shí)做些什么,數(shù)據(jù)沒回來之前做些什么 -->
  <suspense>
      <template #fallback>
          <h1>Loading</h1>
      </template>
      <template #default>
         <HomeCom></HomeCom>
      </template>
  </suspense>
</template>

<script setup>
import * as api from '../api/index'
// vue3異步請(qǐng)求
import { onMounted,defineAsyncComponent } from 'vue';
//異步請(qǐng)求組件
const HomeCom = defineAsyncComponent(()=>import('../components/HomeCom.vue'))
onMounted(async() =>{
    let res = await api.getHomepage()
    //console.log(res);
})
</script>

組件

<template>
    <h1>首頁</h1>
    <ul>
        <li v-for="(item,i) in hero">
            <h3>{{item.category}}</h3>
        </li>
    </ul>
</template>

<script setup>
import * as api from '../api/index'
import { reactive } from 'vue'
let res = await api.getHomepage()
const hero = reactive(res.hero)
</script>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末媳危,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子冈敛,更是在濱河造成了極大的恐慌待笑,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,000評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件抓谴,死亡現(xiàn)場離奇詭異暮蹂,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)癌压,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,745評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門仰泻,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人滩届,你說我怎么就攤上這事集侯。” “怎么了帜消?”我有些...
    開封第一講書人閱讀 168,561評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵棠枉,是天一觀的道長。 經(jīng)常有香客問我券犁,道長术健,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,782評(píng)論 1 298
  • 正文 為了忘掉前任粘衬,我火速辦了婚禮荞估,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘稚新。我一直安慰自己勘伺,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,798評(píng)論 6 397
  • 文/花漫 我一把揭開白布褂删。 她就那樣靜靜地躺著飞醉,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上缅帘,一...
    開封第一講書人閱讀 52,394評(píng)論 1 310
  • 那天轴术,我揣著相機(jī)與錄音,去河邊找鬼钦无。 笑死逗栽,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的失暂。 我是一名探鬼主播彼宠,決...
    沈念sama閱讀 40,952評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼弟塞!你這毒婦竟也來了凭峡?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,852評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤决记,失蹤者是張志新(化名)和其女友劉穎摧冀,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體霉涨,經(jīng)...
    沈念sama閱讀 46,409評(píng)論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡按价,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,483評(píng)論 3 341
  • 正文 我和宋清朗相戀三年惭适,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了笙瑟。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,615評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡癞志,死狀恐怖往枷,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情凄杯,我是刑警寧澤错洁,帶...
    沈念sama閱讀 36,303評(píng)論 5 350
  • 正文 年R本政府宣布,位于F島的核電站戒突,受9級(jí)特大地震影響屯碴,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜膊存,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,979評(píng)論 3 334
  • 文/蒙蒙 一导而、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧隔崎,春花似錦今艺、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,470評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至钓株,卻和暖如春实牡,著一層夾襖步出監(jiān)牢的瞬間陌僵,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,571評(píng)論 1 272
  • 我被黑心中介騙來泰國打工创坞, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留拾弃,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,041評(píng)論 3 377
  • 正文 我出身青樓摆霉,卻偏偏與公主長得像豪椿,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子携栋,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,630評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容