廢話
本篇大概記錄一下,vuex 使用,Vue-router 使用,基本與2.0一樣(下載安裝請移步第一篇)
正文
vuex
默認安裝好,里面是只有一個index.js檔案,和vue2.0一樣,當然你可以直接在index.js里直接去寫,像下圖這樣

也可以適當的擴展一下,例如vue2.0的模塊化寫法是這樣的

咱么就擴展一下,目錄結構如下(就是簡單的分開,不像vue2.0 modules那樣)

index.js
import {
createStore
} from 'vuex'
import state from './state'
import mutations from './mutations'
import actions from './actions'
export default createStore({
state,
mutations,
actions,
modules: {}
})
actions.js
const actions = {
}
export default actions
mutations.js
const mutations = {
setAddress: function (state, value) {
state.userInfo.address = value
}
}
export default mutations
state.js
const state = {
userInfo: {
name: '前端',
age: '18'
}
}
export default state
使用
About.vue

代碼也附上,盡量自己理解之后,寫一遍,熟練了在Ctrl c Ctrl v
<template>
<div>
<h3>測驗vuex</h3>
<button @click="getStore">獲取store里state的值</button>
<div>姓名:{{userInfo.name}}</div>
<div>年齡:{{userInfo.age}}</div>
<div>地址:{{userInfo.address}}</div>
<button @click="addAddress">store操作</button>
</div>
</template>
<script>
import {getCurrentInstance, reactive, toRefs} from 'vue'
export default {
setup () {
const store = reactive({
userInfo:{}
})
// 獲取store里state的值
const { ctx } = getCurrentInstance()
const getStore = ()=>{
store.userInfo = ctx.$store.state.userInfo
}
// 修改
const addAddress = ()=>{
ctx.$store.commit('setAddress', '上海')
}
return {
...toRefs(store),
getStore,
addAddress
}
},
}
</script>
<style lang='less' scoped>
</style>
vue-router
目錄結構
index.js

這是cli5.0 ui面板安裝之后自動初始化的檔案及目錄,我們可以自己手動安裝,手動創建一下,熟悉下他的基礎寫法
main.js

參考,然后use使用即可,熟悉vue2.0的就發現了,options Api里初始化都是new的建構式,3.0的composition Api都是物件形式
頁面中獲取使用router&route
兩種方式(在About.vue里直接寫了)
- 第一種(和2.0相似,vue2.0里的this,換成現在的ctx)
// 獲取路由表
console.log(ctx.$router.options.routes)
//獲取當前路由物件
console.log(ctx.$router.currentRoute.value)
// 獲取當前路由path
//vue2.0 this.$route.path
console.log(ctx.$route) //undefined
但是,ctx. r o u t e 是 u n d e f i n e d , c t x . route 是undefined,ctx. route是undefined,ctx.route.pash自然不行了,所以想獲取當前的path,可以去當前路由物件里去拿
- 第二種(推薦)
//先引入 router
import {useRoute, useRouter} from 'vue-router'
// 獲取路由表
console.log(router.options.routes)
//獲取當前路由物件
console.log(router.currentRoute.value)
// 獲取當前路由path
console.log(route.path)
路由跳轉
// html寫法
<router-link to="/">Home</router-link>
// setup寫法
const toHome = ()=>{
// 兩種寫法都可以
// ctx.$router.push("/")
router.push("/")
}
附上圖片

運行結果

提示
1、composition Api 沒有this,方法里呼叫方法,直接方法名(),即可
2、自己試了下無法在setup中使用map輔助函式了,有興趣的可以試試,還想使用的可以使用2.0的options Api,3.0也是兼容的,不過也不建議過度使用vuex了,可以多使用vue3.0開源的新的底層功能
3、ctx.
r
o
u
t
e
為
u
n
d
e
f
i
n
e
d
,
c
t
x
.
route為undefined,ctx.
route為undefined,ctx.route.path 不可用
下一篇
組件通信使用
推薦檔案
vuex
vue-router
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/265983.html
標籤:區塊鏈
上一篇:ERROR: Cannot find command ‘git‘ - do you have ‘git‘ installed and in your PATH?
