- 路由配置
vue3.0使用createRouter来创建Vue Router实例
之前用构造函数的方式
createRouter, createWebHashHistory
const router = createRouter({
history: createWebHashHistory(),
[
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: () => import('../views/About.vue')
}
]
})
export default router
- 初始化状态
vue3.0通过setup方法初始化状态
调用ref()方法返回一个响应式的对象
在setup中对ref返回的数值进行操作时,需要通过.value来获取
// value1只有一个value属性
setup() {
let value1 = ref('disk')
let ienter = () => {
console.log(value.value);
}
let addValue1 = () => {
value1.value ++
}
return {
value, ienter,addValue1
}
}
- 计算属性computed方法和监听器watch方法
watch方法包含两个参数,两个参数都是function
import { ref, toRefs, computed, watch } from 'vue'
setup() {
let value1 = ref('disk')
let ienter = () => {
console.log(value.value);
}
let addValue1 = () => {
value1.value ++
}
let douValue1 = computed(() => value1.value * 2)
watch(() => value1.value, val=>{
console.log(val)
})
return {
value, ienter,addValue1, douValue1
}
}
- 获取路由
vue3.0通过getCurrentInstance方法获取当前组件的实例
通过getCurrentInstance方法的ctx属性获得当前上下文
通过计算computed获取store.state.name的值
import { ref, toRefs, computed, watch, getCurrentInstance } from 'vue'
setup() {
let value1 = ref('disk')
let ienter = () => {
console.log(value.value);
}
let addValue1 = () => {
value1.value ++
}
let douValue1 = computed(() => value1.value * 2)
watch(() => value1.value, val=>{
console.log(val)
})
const { ctx } = getCurrentInstance()
// 当前路由信息
// ctx.$router.currentRoute.value
return {
value, ienter,addValue1, douValue1
}
}
- Vuex使用
import Vuex from 'vuex'
export default Vuex.createStore({
state: {
name: 'licky'
},
mutations: {
setName(state, payload) {
state.test.a = payload
}
},
actions: {
},
modules: {
}
})
setup() {
let value1 = ref('disk')
let ienter = () => {
console.log(value.value);
}
let addValue1 = () => {
value1.value ++
}
let douValue1 = computed(() => value1.value * 2)
watch(() => value1.value, val=>{
console.log(val)
})
const { ctx } = getCurrentInstance()
// 当前路由信息
// ctx.$router.currentRoute.value
let name = computed(() => ctx.$store.state.name)
let editName = () => {
ctx.$store.commit('setName', 'new Name zzz')
}
return {
value, ienter,addValue1, douValue1, name, editName
}
}
网友评论